repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/cucim.kit.cumed-config.cmake.in
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @PACKAGE_INIT@ # Find dependent libraries # ... include(CMakeFindDependencyMacro) #find_dependency(Boost x.x.x REQUIRED) if(NOT TARGET cumed::cumed) include(${CMAKE_CURRENT_LIST_DIR}/cucim.kit.cumed-targets.cmake) endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/modules/CuCIMUtils.cmake
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Store current BUILD_SHARED_LIBS setting in CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_set_build_shared_libs) macro(cucim_set_build_shared_libs new_value) set(CUCIM_OLD_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}}) if (DEFINED CACHE{BUILD_SHARED_LIBS}) set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED TRUE) else() set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED FALSE) endif() set(BUILD_SHARED_LIBS ${new_value} CACHE BOOL "" FORCE) endmacro() endif() # Restore BUILD_SHARED_LIBS setting from CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_restore_build_shared_libs) macro(cucim_restore_build_shared_libs) if (CUCIM_OLD_BUILD_SHARED_LIBS_CACHED) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS} CACHE BOOL "" FORCE) else() unset(BUILD_SHARED_LIBS CACHE) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS}) endif() endmacro() endif() # Define CMAKE_CUDA_ARCHITECTURES for the given architecture values # # Params: # arch_list - architecture value list (e.g., '60;70;75;80;86') if(NOT COMMAND cucim_define_cuda_architectures) function(cucim_define_cuda_architectures arch_list) set(arch_string "") # Create SASS for all architectures in the list foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${arch}-real") endforeach(arch) # Create PTX for the latest architecture for forward-compatibility. list(GET arch_list -1 latest_arch) foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${latest_arch}-virtual") endforeach(arch) set(CMAKE_CUDA_ARCHITECTURES ${arch_string} PARENT_SCOPE) endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/modules/SuperBuildUtils.cmake
# Apache License, Version 2.0 # Copyright 2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. include(FetchContent) set(CMAKE_SUPERBUILD_DEPS_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/..") if(NOT COMMAND superbuild_depend) function(superbuild_depend module_name) include("${CMAKE_SUPERBUILD_DEPS_ROOT_DIR}/deps/${module_name}.cmake") endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/deps/catch2.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::catch2) FetchContent_Declare( deps-catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.4.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-catch2) if (NOT deps-catch2_POPULATED) message(STATUS "Fetching catch2 sources") FetchContent_Populate(deps-catch2) message(STATUS "Fetching catch2 sources - done") endif () add_subdirectory(${deps-catch2_SOURCE_DIR} ${deps-catch2_BINARY_DIR} EXCLUDE_FROM_ALL) # Include Append catch2's cmake module path so that we can use `include(Catch)`. # https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake list(APPEND CMAKE_MODULE_PATH "${deps-catch2_SOURCE_DIR}/extras") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} PARENT_SCOPE) add_library(deps::catch2 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::catch2 INTERFACE Catch2::Catch2) set(deps-catch2_SOURCE_DIR ${deps-catch2_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-catch2_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/deps/googletest.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googletest) FetchContent_Declare( deps-googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.10.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googletest) if (NOT deps-googletest_POPULATED) message(STATUS "Fetching googletest sources") FetchContent_Populate(deps-googletest) message(STATUS "Fetching googletest sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-googletest_SOURCE_DIR} ${deps-googletest_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googletest INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googletest INTERFACE googletest) set(deps-googletest_SOURCE_DIR ${deps-googletest_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googletest_SOURCE_DIR) endif () #CMake Warning (dev) in cmake-build-debug/_deps/deps-googletest-src/googlemock/CMakeLists.txt: # Policy CMP0082 is not set: Install rules from add_subdirectory() are # interleaved with those in caller. Run "cmake --help-policy CMP0082" for # policy details. Use the cmake_policy command to set the policy and # suppress this warning.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/deps/cli11.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::cli11) FetchContent_Declare( deps-cli11 GIT_REPOSITORY https://github.com/CLIUtils/CLI11.git GIT_TAG v1.9.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-cli11) if (NOT deps-cli11_POPULATED) message(STATUS "Fetching cli11 sources") FetchContent_Populate(deps-cli11) message(STATUS "Fetching cli11 sources - done") endif () add_subdirectory(${deps-cli11_SOURCE_DIR} ${deps-cli11_BINARY_DIR} EXCLUDE_FROM_ALL) add_library(deps::cli11 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::cli11 INTERFACE CLI11::CLI11) set(deps-cli11_SOURCE_DIR ${deps-cli11_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-cli11_SOURCE_DIR) endif () # Note that library had a failure with nvcc compiler and gcc 9.x headers # ...c++/9/tuple(553): error: pack "_UElements" does not have the same number of elements as "_Elements" # __and_<is_nothrow_assignable<_Elements&, _UElements>...>::value; # Not using nvcc for main code that uses cli11 solved the issue.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/deps/googlebenchmark.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googlebenchmark) FetchContent_Declare( deps-googlebenchmark GIT_REPOSITORY https://github.com/google/benchmark.git GIT_TAG v1.5.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googlebenchmark) if (NOT deps-googlebenchmark_POPULATED) message(STATUS "Fetching googlebenchmark sources") FetchContent_Populate(deps-googlebenchmark) message(STATUS "Fetching googlebenchmark sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) set(BENCHMARK_ENABLE_GTEST_TESTS OFF) add_subdirectory(${deps-googlebenchmark_SOURCE_DIR} ${deps-googlebenchmark_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googlebenchmark INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googlebenchmark INTERFACE benchmark::benchmark) set(deps-googlebenchmark_SOURCE_DIR ${deps-googlebenchmark_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googlebenchmark_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/cmake/deps/fmt.cmake
# Apache License, Version 2.0 # Copyright 2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::fmt) FetchContent_Declare( deps-fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 7.0.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-fmt) if (NOT deps-fmt_POPULATED) message(STATUS "Fetching fmt sources") FetchContent_Populate(deps-fmt) message(STATUS "Fetching fmt sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-fmt_SOURCE_DIR} ${deps-fmt_BINARY_DIR} EXCLUDE_FROM_ALL) # Set PIC to prevent the following error message # : /usr/bin/ld: ../lib/libfmtd.a(format.cc.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC set_target_properties(fmt PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::fmt INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::fmt INTERFACE fmt::fmt-header-only) set(deps-fmt_SOURCE_DIR ${deps-fmt_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-fmt_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/src
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/src/cumed/cumed.cpp
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define CUCIM_EXPORTS #include "cumed.h" #include <fcntl.h> #include <filesystem> #include <fmt/format.h> #include <cucim/core/framework.h> #include <cucim/core/plugin_util.h> #include <cucim/filesystem/file_path.h> #include <cucim/io/format/image_format.h> #include <cucim/memory/memory_manager.h> const struct cucim::PluginImplDesc kPluginImpl = { "cucim.kit.cumed", // name { 0, 1, 0 }, // version "dev", // build "clara team", // author "cumed", // description "cumed plugin", // long_description "Apache-2.0", // license "https://github.com/rapidsai/cucim", // url "linux", // platforms, cucim::PluginHotReload::kDisabled, // hot_reload }; // Using CARB_PLUGIN_IMPL_MINIMAL instead of CARB_PLUGIN_IMPL // This minimal macro doesn't define global variables for logging, profiler, crash reporting, // and also doesn't call for the client registration for those systems CUCIM_PLUGIN_IMPL_MINIMAL(kPluginImpl, cucim::io::format::IImageFormat) CUCIM_PLUGIN_IMPL_NO_DEPS() static void set_enabled(bool val) { (void)val; } static bool is_enabled() { return true; } static const char* get_format_name() { return "MetaIO"; } static bool CUCIM_ABI checker_is_valid(const char* file_name, const char* buf, size_t size) { (void)buf; (void)size; auto file = std::filesystem::path(file_name); auto extension = file.extension().string(); if (extension.compare(".mhd") == 0) { return true; } return false; } static CuCIMFileHandle_share CUCIM_ABI parser_open(const char* file_path_) { const cucim::filesystem::Path& file_path = file_path_; int mode = O_RDONLY; // Copy file path (Allocated memory would be freed at close() method.) char* file_path_cstr = static_cast<char*>(malloc(file_path.size() + 1)); (void)file_path_cstr; memcpy(file_path_cstr, file_path.c_str(), file_path.size()); file_path_cstr[file_path.size()] = '\0'; int fd = ::open(file_path_cstr, mode, 0666); if (fd == -1) { cucim_free(file_path_cstr); throw std::invalid_argument(fmt::format("Cannot open {}!", file_path)); } auto file_handle = std::make_shared<CuCIMFileHandle>(fd, nullptr, FileHandleType::kPosix, file_path_cstr, nullptr); CuCIMFileHandle_share handle = new std::shared_ptr<CuCIMFileHandle>(std::move(file_handle)); return handle; } static bool CUCIM_ABI parser_parse(CuCIMFileHandle_ptr handle, cucim::io::format::ImageMetadataDesc* out_metadata_desc) { (void)handle; if (!out_metadata_desc || !out_metadata_desc->handle) { throw std::runtime_error("out_metadata_desc shouldn't be nullptr!"); } cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); // // Metadata Setup // // Note: int-> uint16_t due to type differences between ImageMetadataDesc.ndim and DLTensor.ndim const uint16_t ndim = 3; auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; std::pmr::vector<int64_t> shape({ 256, 256, 3 }, &resource); DLDataType dtype{ kDLUInt, 8, 1 }; // Assume RGB std::pmr::vector<std::string_view> channel_names( { std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource); std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); spacing.insert(spacing.end(), ndim, 1.0); std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); spacing_units.emplace_back(std::string_view{ "pixel" }); spacing_units.emplace_back(std::string_view{ "pixel" }); spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; size_t level_count = 1; const uint16_t level_ndim = 2; // {'X', 'Y'} std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { level_dimensions.emplace_back(256); level_dimensions.emplace_back(256); } std::pmr::vector<float> level_downsamples(&resource); for (size_t i = 0; i < level_count; ++i) { level_downsamples.emplace_back(1.0); } std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { level_tile_sizes.emplace_back(256); level_tile_sizes.emplace_back(256); } const size_t associated_image_count = 0; std::pmr::vector<std::string_view> associated_image_names(&resource); std::string_view raw_data{ "" }; // Dynamically allocate memory for json_data (need to be freed manually); const std::string& json_str = std::string{}; char* json_data_ptr = static_cast<char*>(cucim_malloc(json_str.size() + 1)); memcpy(json_data_ptr, json_str.data(), json_str.size() + 1); std::string_view json_data{ json_data_ptr, json_str.size() }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(level_count); out_metadata.level_ndim(level_ndim); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); return true; } static bool CUCIM_ABI parser_close(CuCIMFileHandle_ptr handle_ptr) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); if (handle->client_data) { // TODO: comment out and reinterpret_cast when needed. // delete reinterpret_cast<xx*>(handle->client_data); handle->client_data = nullptr; } return true; } static bool CUCIM_ABI reader_read(const CuCIMFileHandle_ptr handle_ptr, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata_desc = nullptr) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); (void)handle; (void)metadata; std::string device_name(request->device); if (request->shm_name) { device_name = device_name + fmt::format("[{}]", request->shm_name); // TODO: check performance } cucim::io::Device out_device(device_name); uint8_t* raster = nullptr; uint32_t width = 256; uint32_t height = 256; uint32_t samples_per_pixel = 3; size_t raster_size = width * height * samples_per_pixel; // Raw metadata for the associated image const char* raw_data_ptr = nullptr; size_t raw_data_len = 0; // Json metadata for the associated image char* json_data_ptr = nullptr; // Populate image data const uint16_t ndim = 3; int64_t* container_shape = static_cast<int64_t*>(cucim_malloc(sizeof(int64_t) * ndim)); container_shape[0] = height; container_shape[1] = width; container_shape[2] = 3; // hard-coded for 'C' // Copy the raster memory and free it if needed. cucim::memory::move_raster_from_host((void**)&raster, raster_size, out_device); auto& out_image_container = out_image_data->container; out_image_container.data = raster; out_image_container.device = DLDevice{ static_cast<DLDeviceType>(out_device.type()), out_device.index() }; out_image_container.ndim = ndim; out_image_container.dtype = { kDLUInt, 8, 1 }; out_image_container.shape = container_shape; out_image_container.strides = nullptr; // Tensor is compact and row-majored out_image_container.byte_offset = 0; auto& shm_name = out_device.shm_name(); size_t shm_name_len = shm_name.size(); if (shm_name_len != 0) { out_image_data->shm_name = static_cast<char*>(cucim_malloc(shm_name_len + 1)); memcpy(out_image_data->shm_name, shm_name.c_str(), shm_name_len + 1); } else { out_image_data->shm_name = nullptr; } // Populate metadata if (out_metadata_desc && out_metadata_desc->handle) { cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; std::pmr::vector<int64_t> shape(&resource); shape.reserve(ndim); shape.insert(shape.end(), &container_shape[0], &container_shape[ndim]); DLDataType dtype{ kDLUInt, 8, 1 }; // TODO: Do not assume channel names as 'RGB' std::pmr::vector<std::string_view> channel_names( { std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource); // We don't know physical pixel size for associated image so fill it with default value 1 std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); spacing.insert(spacing.end(), ndim, 1.0); std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; // Manually set resolution dimensions to 2 const uint16_t level_ndim = 2; std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_ndim * 1); // it has only one size level_dimensions.emplace_back(shape[1]); // width level_dimensions.emplace_back(shape[0]); // height std::pmr::vector<float> level_downsamples(&resource); level_downsamples.reserve(1); level_downsamples.emplace_back(1.0); std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_ndim * 1); // it has only one size level_tile_sizes.emplace_back(shape[1]); // tile_width level_tile_sizes.emplace_back(shape[0]); // tile_height // Empty associated images const size_t associated_image_count = 0; std::pmr::vector<std::string_view> associated_image_names(&resource); std::string_view raw_data{ raw_data_ptr ? raw_data_ptr : "", raw_data_len }; std::string_view json_data{ json_data_ptr ? json_data_ptr : "" }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(1); out_metadata.level_ndim(2); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); } return true; } static bool CUCIM_ABI writer_write(const CuCIMFileHandle_ptr handle_ptr, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageDataDesc* image_data) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); (void)handle; (void)metadata; (void)image_data; return true; } void fill_interface(cucim::io::format::IImageFormat& iface) { static cucim::io::format::ImageCheckerDesc image_checker = { 0, 0, checker_is_valid }; static cucim::io::format::ImageParserDesc image_parser = { parser_open, parser_parse, parser_close }; static cucim::io::format::ImageReaderDesc image_reader = { reader_read }; static cucim::io::format::ImageWriterDesc image_writer = { writer_write }; // clang-format off static cucim::io::format::ImageFormatDesc image_format_desc = { set_enabled, is_enabled, get_format_name, image_checker, image_parser, image_reader, image_writer }; // clang-format on // clang-format off iface = { &image_format_desc, 1 }; // clang-format on }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/src
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cumed/src/cumed/cumed.h
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUMED_CUMED_H #define CUMED_CUMED_H #endif // CUMED_CUMED_H
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/CMakeLists.txt
# Apache License, Version 2.0 # Copyright 2020-2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # CUDA_STANDARD 17 is supported from CMAKE 3.18 # : https://cmake.org/cmake/help/v3.18/prop_tgt/CUDA_STANDARD.html cmake_minimum_required(VERSION 3.18) ################################################################################ # Prerequisite statements ################################################################################ # Set VERSION unset(VERSION CACHE) file(STRINGS ${CMAKE_CURRENT_LIST_DIR}/../../../VERSION VERSION) # strip alpha version info string(REGEX REPLACE "a.*$" "" VERSION ${VERSION}) # Append local cmake module path list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake/modules") project(cuslide VERSION ${VERSION} DESCRIPTION "cuslide" LANGUAGES C CXX) set(CUCIM_PLUGIN_NAME "cucim.kit.cuslide") ################################################################################ # Include utilities ################################################################################ include(SuperBuildUtils) include(CuCIMUtils) ################################################################################ # Set cmake policy ################################################################################ if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.19") cmake_policy(SET CMP0110 NEW) # For add_test() to support arbitrary characters in test name endif() ################################################################################ # Basic setup ################################################################################ # Set default build type set(DEFAULT_BUILD_TYPE "Release") if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to '${DEFAULT_BUILD_TYPE}' as none was specified.") set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}" CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif () # Set default output directories if (NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib") endif() if (NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/lib") endif() if (NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/bin") endif() # Find CUDAToolkit as rmm depends on it find_package(CUDAToolkit REQUIRED) # For Threads::Threads find_package(Threads REQUIRED) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED YES) # Include CUDA headers explicitly for VSCode intelli-sense include_directories(AFTER SYSTEM ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) # Disable visibility to not expose unnecessary symbols set(CMAKE_CXX_VISIBILITY_PRESET hidden) set(CMAKE_VISIBILITY_INLINES_HIDDEN YES) # Set RPATH if (NOT APPLE) set(CMAKE_INSTALL_RPATH $ORIGIN) endif() # Set Installation setup if (NOT CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_LIST_DIR}/install) # CACHE PATH "install here" FORCE) endif () include(GNUInstallDirs) # Force to set CMAKE_INSTALL_LIBDIR to lib as the library can be built with Cent OS ('lib64' is set) and # /usr/local/lib64 or /usr/local/lib is not part of ld.so.conf* (`cat /etc/ld.so.conf.d/* | grep lib64`) # https://gitlab.kitware.com/cmake/cmake/-/issues/20565 set(CMAKE_INSTALL_LIBDIR lib) include(ExternalProject) ################################################################################ # Options ################################################################################ # Setup CXX11 ABI # : Adds CXX11 ABI definition to the compiler command line for targets in the current directory, # whether added before or after this command is invoked, and for the ones in sub-directories added after. add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0) # TODO: create two library, one with CXX11 ABI and one without it. ################################################################################ # Define dependencies ################################################################################ superbuild_depend(fmt) superbuild_depend(libjpeg-turbo) # libjpeg-turbo should be located before libtiff as libtiff depends on libjpeg-turbo superbuild_depend(libopenjpeg) superbuild_depend(libtiff) superbuild_depend(catch2) superbuild_depend(openslide) superbuild_depend(googletest) superbuild_depend(googlebenchmark) superbuild_depend(cli11) superbuild_depend(pugixml) superbuild_depend(json) superbuild_depend(libdeflate) superbuild_depend(nvjpeg) superbuild_depend(libculibos) ################################################################################ # Find cucim package ################################################################################ if (NOT CUCIM_SDK_PATH) get_filename_component(CUCIM_SDK_PATH "${CMAKE_SOURCE_DIR}/../../.." ABSOLUTE) message("CUCIM_SDK_PATH is not set. Using '${CUCIM_SDK_PATH}'") else() message("CUCIM_SDK_PATH is set to ${CUCIM_SDK_PATH}") endif() find_package(cucim CONFIG REQUIRED HINTS ${CUCIM_SDK_PATH}/install/${CMAKE_INSTALL_LIBDIR}/cmake/cucim $ENV{PREFIX}/include/cmake/cucim # In case conda build is used ) ################################################################################ # Define compile options ################################################################################ if(NOT BUILD_SHARED_LIBS) set(BUILD_SHARED_LIBS ON) endif() ################################################################################ # Add library: cucim ################################################################################ # Add library add_library(${CUCIM_PLUGIN_NAME} src/cuslide/cuslide.cpp src/cuslide/cuslide.h src/cuslide/deflate/deflate.cpp src/cuslide/deflate/deflate.h src/cuslide/jpeg/libjpeg_turbo.cpp src/cuslide/jpeg/libjpeg_turbo.h src/cuslide/jpeg/libnvjpeg.cpp src/cuslide/jpeg/libnvjpeg.h src/cuslide/jpeg2k/color_conversion.cpp src/cuslide/jpeg2k/color_conversion.h src/cuslide/jpeg2k/color_table.h src/cuslide/jpeg2k/libopenjpeg.cpp src/cuslide/jpeg2k/libopenjpeg.h src/cuslide/loader/nvjpeg_processor.cpp src/cuslide/loader/nvjpeg_processor.h ${deps-libopenjpeg_SOURCE_DIR}/src/bin/common/color.c # for color_sycc_to_rgb() and color_apply_icc_profile() src/cuslide/lzw/lzw.cpp src/cuslide/lzw/lzw.h src/cuslide/lzw/lzw_libtiff.cpp src/cuslide/lzw/lzw_libtiff.h src/cuslide/raw/raw.cpp src/cuslide/raw/raw.h src/cuslide/tiff/ifd.cpp src/cuslide/tiff/ifd.h src/cuslide/tiff/tiff.cpp src/cuslide/tiff/tiff.h src/cuslide/tiff/types.h) # compile color.c for libopenjpeg with c++ set_source_files_properties(${deps-libopenjpeg_SOURCE_DIR}/src/bin/common/color.c PROPERTIES LANGUAGE C CMAKE_CXX_VISIBILITY_PRESET default CMAKE_C_VISIBILITY_PRESET default CMAKE_VISIBILITY_INLINES_HIDDEN OFF) # Ignore warnings in existing source code from libjpeg-turbo set_source_files_properties(src/cuslide/jpeg/libjpeg_turbo.cpp PROPERTIES COMPILE_OPTIONS "-Wno-error" # or, "-Wno-write-strings;-Wno-clobbered" ) # Compile options set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO SOVERSION ${PROJECT_VERSION_MAJOR} VERSION ${PROJECT_VERSION} ) target_compile_features(${CUCIM_PLUGIN_NAME} PRIVATE cxx_std_17) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(${CUCIM_PLUGIN_NAME} PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) # Link libraries target_link_libraries(${CUCIM_PLUGIN_NAME} PRIVATE # Use custom nvjpeg_static that supports GPU input (>= CUDA 11.6) deps::nvjpeg_static # add this before cudart so that nvjpeg.h in static library takes precedence. # Add CUDA::culibos to link necessary methods for 'deps::nvjpeg_static' CUDA::culibos # for nvjpeg CUDA::cudart deps::fmt cucim::cucim deps::libtiff deps::libjpeg-turbo deps::libopenjpeg deps::libopenjpeg-lcms2 deps::pugixml deps::json deps::libdeflate ) target_include_directories(${CUCIM_PLUGIN_NAME} PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src ) # Do not generate SONAME as this would be used as plugin # Need to use IMPORTED_NO_SONAME when using this .so file. set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES NO_SONAME 1) # Prevent relative path problem of .so with no DT_SONAME. # : https://stackoverflow.com/questions/27261288/cmake-linking-shared-c-object-from-externalproject-produces-binaries-with-rel target_link_options(${CUCIM_PLUGIN_NAME} PRIVATE "LINKER:-soname=${CUCIM_PLUGIN_NAME}@${PROJECT_VERSION}.so") # Do not add 'lib' prefix for the library set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES PREFIX "") # Postfix version set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES OUTPUT_NAME "${CUCIM_PLUGIN_NAME}@${PROJECT_VERSION}") #set_target_properties(${CUCIM_PLUGIN_NAME} PROPERTIES LINK_FLAGS # "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/cuslide.map") ################################################################################ # Add tests #########################################################std####################### add_subdirectory(tests) add_subdirectory(benchmarks) ################################################################################ # Install ################################################################################ set(INSTALL_TARGETS ${CUCIM_PLUGIN_NAME} cuslide_tests cuslide_benchmarks ) install(TARGETS ${INSTALL_TARGETS} EXPORT ${CUCIM_PLUGIN_NAME}-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Runtime LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Runtime NAMELINK_COMPONENT ${CUCIM_PLUGIN_NAME}_Development ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${CUCIM_PLUGIN_NAME}_Development ) # Currently cuslide plugin doesn't have include path so comment out # install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT ${CUCIM_PLUGIN_NAME}-targets FILE ${CUCIM_PLUGIN_NAME}-targets.cmake NAMESPACE ${PROJECT_NAME}:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME}) # Write package configs include(CMakePackageConfigHelpers) configure_package_config_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) set(CMAKE_EXPORT_PACKAGE_REGISTRY ON) export(PACKAGE ${CUCIM_PLUGIN_NAME}) # Write package configs include(CMakePackageConfigHelpers) configure_package_config_file( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config.cmake ${CMAKE_CURRENT_BINARY_DIR}/cmake/${CUCIM_PLUGIN_NAME}-config-version.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${CUCIM_PLUGIN_NAME} ) set(CMAKE_EXPORT_PACKAGE_REGISTRY ON) # TODO: duplicate? export(PACKAGE ${CUCIM_PLUGIN_NAME}) unset(BUILD_SHARED_LIBS CACHE)
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.editorconfig
[*] indent_style = space indent_size = 4 charset = utf-8 trim_trailing_whitespace = true max_line_length = 120 insert_final_newline = true
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.clang-format
AccessModifierOffset: -4 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false AlignConsecutiveDeclarations: false AlignEscapedNewlinesLeft: false AlignTrailingComments: false AllowAllParametersOfDeclarationOnNextLine: true AllowShortFunctionsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false AllowShortCaseLabelsOnASingleLine : false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: false AlwaysBreakBeforeMultilineStrings: true AlwaysBreakTemplateDeclarations: true BinPackArguments: true BinPackParameters: false BreakBeforeBinaryOperators: false BreakBeforeBraces: Custom BraceWrapping: AfterClass: true AfterControlStatement: true AfterEnum: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: true AfterStruct: true AfterUnion: true AfterExternBlock: true BeforeCatch: true BeforeElse: true IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace : true BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false BreakStringLiterals: false ColumnLimit: 120 CommentPragmas: '' ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: false DerivePointerBinding: false FixNamespaceComments: true IndentCaseLabels: false IndentPPDirectives: AfterHash IndentFunctionDeclarationAfterType: false IndentWidth: 4 SortIncludes: false IncludeCategories: - Regex: '[<"](.*\/)?Defines.h[>"]' Priority: 1 # - Regex: '<cuslide\/.+>' # Priority: 3 - Regex: '<[[:alnum:]_.]+>' Priority: 5 - Regex: '<[[:alnum:]_.\/]+>' Priority: 4 - Regex: '".*"' Priority: 2 IncludeBlocks: Regroup Language: Cpp MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: true PenaltyBreakBeforeFirstCallParameter: 0 PenaltyBreakComment: 1 PenaltyBreakFirstLessLess: 0 PenaltyBreakString: 1 PenaltyExcessCharacter: 10 PenaltyReturnTypeOnItsOwnLine: 1000 PointerAlignment: Left SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInCStyleCastParentheses: false SpacesInContainerLiterals: false SpacesInParentheses: false Standard: Cpp11 ReflowComments: true TabWidth: 4 UseTab: Never
0
rapidsai_public_repos/cucim/cpp/plugins
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cuslide.map
CUSLIDE_0.1 { local: *; };
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.vscode/settings.json
{ "cmake.sourceDirectory": "${workspaceFolder}/.", "cmake.buildDirectory": "${workspaceFolder}/build-debug" }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/config.h
/* * Apache License, Version 2.0 * Copyright 2020-2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_TESTS_CONFIG_H #define CUSLIDE_TESTS_CONFIG_H #include <string> #include <cstdlib> struct AppConfig { std::string test_folder; std::string test_file; std::string temp_folder = "/tmp"; std::string get_input_path(const std::string default_value = "generated/tiff_stripe_4096x4096_256.tif") const { // If `test_file` is absolute path if (!test_folder.empty() && test_file.substr(0, 1) == "/") { return test_file; } else { std::string test_data_folder = test_folder; if (test_data_folder.empty()) { if (const char* env_p = std::getenv("CUCIM_TESTDATA_FOLDER")) { test_data_folder = env_p; } else { test_data_folder = "test_data"; } } if (test_file.empty()) { return test_data_folder + "/" + default_value; } else { return test_data_folder + "/" + test_file; } } } }; extern AppConfig g_config; #endif // CUSLIDE_TESTS_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/test_philips_tiff.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cucim/memory/memory_manager.h> #include <openslide/openslide.h> #include "cuslide/tiff/tiff.h" #include "config.h" #include <catch2/catch_test_macros.hpp> #include <chrono> TEST_CASE("Verify philips tiff file", "[test_philips_tiff.cpp]") { auto tif = std::make_shared<cuslide::tiff::TIFF>(g_config.get_input_path("private/philips_tiff_000.tif").c_str(), O_RDONLY); // , cuslide::tiff::TIFF::kUseLibTiff tif->construct_ifds(); int64_t test_sx = 0; int64_t test_sy = 0; int64_t test_width = 500; int64_t test_height = 500; cucim::io::format::ImageMetadata metadata{}; cucim::io::format::ImageReaderRegionRequestDesc request{}; cucim::io::format::ImageDataDesc image_data{}; metadata.level_count(1).level_downsamples({ 1.0 }).level_ndim(3); int64_t request_location[2] = { test_sx, test_sy }; request.location = request_location; request.level = 0; int64_t request_size[2] = { test_width, test_height }; request.size = request_size; request.device = const_cast<char*>("cpu"); tif->read(&metadata.desc(), &request, &image_data); request.associated_image_name = const_cast<char*>("label"); tif->read(&metadata.desc(), &request, &image_data, nullptr /*out_metadata*/); tif->close(); REQUIRE(1 == 1); }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/CMakeLists.txt
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include(CTest) enable_testing() ################################################################################ # Add executable: cuslide_tests ################################################################################ add_executable(cuslide_tests config.h main.cpp test_read_region.cpp test_read_rawtiff.cpp test_philips_tiff.cpp ) set_target_properties(cuslide_tests PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) target_compile_features(cuslide_tests PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(cuslide_tests PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) target_compile_definitions(cuslide_tests PUBLIC CUSLIDE_VERSION=${PROJECT_VERSION} CUSLIDE_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUSLIDE_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUSLIDE_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUSLIDE_VERSION_BUILD=${PROJECT_VERSION_BUILD} ) target_link_libraries(cuslide_tests PRIVATE CUDA::cudart cucim::cucim ${CUCIM_PLUGIN_NAME} deps::catch2 deps::openslide deps::cli11 deps::fmt ) # Add headers in src target_include_directories(cuslide_tests PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../src> ) include(Catch) # See https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake for other options catch_discover_tests(cuslide_tests)
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/test_read_region.cpp
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <chrono> #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> #include <openslide/openslide.h> #include <cucim/memory/memory_manager.h> #include "config.h" #include "cuslide/tiff/tiff.h" TEST_CASE("Verify read_region()", "[test_read_region.cpp]") { SECTION("Test with different parameters") { auto test_sx = GENERATE(as<int64_t>{}, 1, 255, 256, 511, 512); auto test_sy = GENERATE(as<int64_t>{}, 1, 255, 256, 511, 512); auto test_width = GENERATE(as<int64_t>{}, 1, 255, 256, 511, 512); auto test_height = GENERATE(as<int64_t>{}, 1, 255, 256, 511, 512); INFO("Execute with [sx:" << test_sx << ", sy:" << test_sy << ", width:" << test_width << ", height:" << test_height << "]"); int openslide_count = 0; int cucim_count = 0; printf("[sx:%ld, sy:%ld, width:%ld, height:%ld]\n", test_sx, test_sy, test_width, test_height); { auto start = std::chrono::high_resolution_clock::now(); openslide_t* slide = openslide_open(g_config.get_input_path().c_str()); REQUIRE(slide != nullptr); auto buf = static_cast<uint32_t*>(cucim_malloc(test_width * test_height * 4)); openslide_read_region(slide, buf, test_sx, test_sy, 0, test_width, test_height); openslide_close(slide); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); printf("openslide: %f\n", elapsed_seconds.count()); auto out_image = reinterpret_cast<uint8_t*>(buf); for (int i = 0; i < test_width * test_height * 4; i += 4) { openslide_count += out_image[i] + out_image[i + 1] + out_image[i + 2]; } INFO("openslide value count: " << openslide_count); cucim_free(buf); } { auto start = std::chrono::high_resolution_clock::now(); auto tif = std::make_shared<cuslide::tiff::TIFF>(g_config.get_input_path().c_str(), O_RDONLY); // , cuslide::tiff::TIFF::kUseLibTiff tif->construct_ifds(); cucim::io::format::ImageMetadata metadata{}; cucim::io::format::ImageReaderRegionRequestDesc request{}; cucim::io::format::ImageDataDesc image_data{}; metadata.level_count(1).level_downsamples({ 1.0 }).level_ndim(3); int64_t request_location[2] = { test_sx, test_sy }; request.location = request_location; request.level = 0; int64_t request_size[2] = { test_width, test_height }; request.size = request_size; request.device = const_cast<char*>("cpu"); tif->read(&metadata.desc(), &request, &image_data); tif->close(); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); printf("cucim: %f\n", elapsed_seconds.count()); auto out_image = reinterpret_cast<uint8_t*>(image_data.container.data); for (int i = 0; i < test_width * test_height * 3; i += 3) { cucim_count += out_image[i] + out_image[i + 1] + out_image[i + 2]; } INFO("cucim value count: " << cucim_count); cucim_free(image_data.container.data); printf("\n"); } REQUIRE(openslide_count == cucim_count); /** * Note: Experiment with OpenSlide with various level values (2020-09-28) * * When other level (1~) is used (for example, sx=4, sy=4, level=2, assuming that down factor is 4 for * level 2), openslide's output is same with the values of cuCIM on the start position (sx/4, sy/4). If sx and * sy is not multiple of 4, openslide's output was not trivial and performance was low. */ } }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/main.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define CATCH_CONFIG_MAIN // #include <catch2/catch_test_macros.hpp> // Implement main explicitly to handle additional parameters. #define CATCH_CONFIG_RUNNER #include "config.h" #include "cucim/core/framework.h" #include <catch2/catch_test_macros.hpp> #include <catch2/catch_session.hpp> #include <string> #include <fmt/format.h> CUCIM_FRAMEWORK_GLOBALS("sample.app") // Global config object AppConfig g_config; /** * Extract `--[option]` or `--[option]=` string from command and set the value to g_config object. * * @param argc number of arguments used for command * @param argv arguments for command * @param obj object reference to modify * @param argument name of argument(option) * @return true if it extracted the value for the option */ static bool extract_test_file_option(int* argc, char** argv, std::string& obj, const char* argument) { std::string arg_str = fmt::format("--{}=", argument); // test_file => --test_file= std::string arg_str2 = fmt::format("--{}", argument); // test_file => --test_file char* value_ptr = nullptr; for (int i = 1; argc && i < *argc; ++i) { if (strncmp(argv[i], arg_str.c_str(), arg_str.size()) == 0) { value_ptr = &argv[i][arg_str.size()]; for (int j = i + 1; argc && j < *argc; ++j) { argv[j - 1] = argv[j]; } --(*argc); argv[*argc] = nullptr; break; } if (strncmp(argv[i], arg_str2.c_str(), arg_str2.size()) == 0 && i + 1 < *argc) { value_ptr = argv[i + 1]; for (int j = i + 2; argc && j < *argc; ++j) { argv[j - 2] = argv[j]; } *argc -= 2; argv[*argc] = nullptr; argv[*argc + 1] = nullptr; break; } } if (value_ptr) { obj = value_ptr; return true; } else { return false; } } int main (int argc, char** argv) { extract_test_file_option(&argc, argv, g_config.test_folder, "test_folder"); extract_test_file_option(&argc, argv, g_config.test_file, "test_file"); extract_test_file_option(&argc, argv, g_config.temp_folder, "temp_folder"); printf("Target test folder: %s (use --test_folder option to change this)\n", g_config.test_folder.c_str()); printf("Target test file : %s (use --test_file option to change this)\n", g_config.test_file.c_str()); printf("Temp folder : %s (use --temp_folder option to change this)\n", g_config.temp_folder.c_str()); int result = Catch::Session().run(argc, argv); return result; }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/tests/test_read_rawtiff.cpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <openslide/openslide.h> #include "cuslide/tiff/tiff.h" #include "config.h" #include <cuda_runtime.h> #include <catch2/catch_test_macros.hpp> #include <fmt/format.h> #include <cucim/filesystem/cufile_driver.h> #include <cstdlib> #include <ctime> #include <fcntl.h> #include <unistd.h> #include <string_view> #include <cucim/logger/timer.h> #include <iostream> #include <fstream> #include <sys/stat.h> #include <sys/mman.h> #define ALIGN_UP(x, align_to) (((uint64_t)(x) + ((uint64_t)(align_to)-1)) & ~((uint64_t)(align_to)-1)) #define ALIGN_DOWN(x, align_to) ((uint64_t)(x) & ~((uint64_t)(align_to)-1)) #define CUDA_ERROR(stmt) \ { \ cuda_status = stmt; \ if (cudaSuccess != cuda_status) \ { \ INFO(fmt::format("Error message: {}", cudaGetErrorString(cuda_status))); \ REQUIRE(cudaSuccess == cuda_status); \ } \ } #define POSIX_ERROR(stmt) \ { \ err = stmt; \ if (err < 0) \ { \ INFO(fmt::format("Error message: {}", std::strerror(errno))); \ REQUIRE(err >= 0); \ } \ } static void shuffle_offsets(uint32_t count, uint64_t* offsets, uint64_t* bytecounts) { // Fisher-Yates shuffle for (uint32_t i = 0; i < count; ++i) { int j = (std::rand() % (count - i)) + i; std::swap(offsets[i], offsets[j]); std::swap(bytecounts[i], bytecounts[j]); } } TEST_CASE("Verify raw tiff read", "[test_read_rawtiff.cpp]") { // cudaError_t cuda_status; // int err; constexpr int BLOCK_SECTOR_SIZE = 4096; constexpr bool SHUFFLE_LIST = true; // constexpr int iter_max = 32; // constexpr int skip_count = 2; constexpr int iter_max = 1; constexpr int skip_count = 0; std::srand(std::time(nullptr)); auto input_file = g_config.get_input_path(); struct stat sb; auto fd_temp = ::open(input_file.c_str(), O_RDONLY); fstat(fd_temp, &sb); uint64_t test_file_size = sb.st_size; ::close(fd_temp); auto tif = std::make_shared<cuslide::tiff::TIFF>(input_file, O_RDONLY); // , cuslide::tiff::TIFF::kUseLibTiff tif->construct_ifds(); tif->ifd(0)->write_offsets_(input_file.c_str()); std::ifstream offsets(fmt::format("{}.offsets", input_file), std::ios::in | std::ios::binary); std::ifstream bytecounts(fmt::format("{}.bytecounts", input_file), std::ios::in | std::ios::binary); // Read image piece count uint32_t image_piece_count_ = 0; offsets.read(reinterpret_cast<char*>(&image_piece_count_), sizeof(image_piece_count_)); bytecounts.read(reinterpret_cast<char*>(&image_piece_count_), sizeof(image_piece_count_)); uint64_t image_piece_offsets_[image_piece_count_]; uint64_t image_piece_bytecounts_[image_piece_count_]; uint64_t min_bytecount = 9999999999; uint64_t max_bytecount = 0; uint64_t sum_bytecount = 0; uint64_t min_offset = 9999999999; uint64_t max_offset = 0; for (uint32_t i = 0; i < image_piece_count_; i++) { offsets.read((char*)&image_piece_offsets_[i], sizeof(image_piece_offsets_[i])); bytecounts.read((char*)&image_piece_bytecounts_[i], sizeof(image_piece_bytecounts_[i])); min_bytecount = std::min(min_bytecount, image_piece_bytecounts_[i]); max_bytecount = std::max(max_bytecount, image_piece_bytecounts_[i]); sum_bytecount += image_piece_bytecounts_[i]; min_offset = std::min(min_offset, image_piece_offsets_[i]); max_offset = std::max(max_offset, image_piece_offsets_[i] + image_piece_bytecounts_[i]); } bytecounts.close(); offsets.close(); fmt::print("file_size : {}\n", test_file_size); fmt::print("min_bytecount: {}\n", min_bytecount); fmt::print("max_bytecount: {}\n", max_bytecount); fmt::print("avg_bytecount: {}\n", static_cast<double>(sum_bytecount) / image_piece_count_); fmt::print("min_offset : {}\n", min_offset); fmt::print("max_offset : {}\n", max_offset); // Shuffle offsets if (SHUFFLE_LIST) { shuffle_offsets(image_piece_count_, image_piece_offsets_, image_piece_bytecounts_); } // Allocate memory uint8_t* unaligned_host = static_cast<uint8_t*>(malloc(test_file_size + BLOCK_SECTOR_SIZE * 2)); uint8_t* buffer_host = static_cast<uint8_t*>(malloc(test_file_size + BLOCK_SECTOR_SIZE * 2)); uint8_t* aligned_host = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_host, BLOCK_SECTOR_SIZE)); // uint8_t* unaligned_device; // CUDA_ERROR(cudaMalloc(&unaligned_device, test_file_size + BLOCK_SECTOR_SIZE)); // uint8_t* aligned_device = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device, BLOCK_SECTOR_SIZE)); // // uint8_t* unaligned_device_host; // CUDA_ERROR(cudaMallocHost(&unaligned_device_host, test_file_size + BLOCK_SECTOR_SIZE)); // uint8_t* aligned_device_host = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device_host, BLOCK_SECTOR_SIZE)); // // uint8_t* unaligned_device_managed; // CUDA_ERROR(cudaMallocManaged(&unaligned_device_managed, test_file_size + BLOCK_SECTOR_SIZE)); // uint8_t* aligned_device_managed = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device_managed, // BLOCK_SECTOR_SIZE)); cucim::filesystem::discard_page_cache(input_file.c_str()); fmt::print("count:{} \n", image_piece_count_); SECTION("Regular POSIX") { fmt::print("Regular POSIX\n"); double total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rpn"); { cucim::logger::Timer timer("- read whole : {:.7f}\n", true, false); fd->pread(aligned_host, test_file_size, 0); double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Read whole average: {}\n", total_elapsed_time / (iter_max - skip_count)); total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rpn"); { cucim::logger::Timer timer("- read tiles : {:.7f}\n", true, false); for (uint32_t i = 0; i < image_piece_count_; ++i) { fd->pread(aligned_host, image_piece_bytecounts_[i], image_piece_offsets_[i]); } double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Read tiles average: {}\n", total_elapsed_time / (iter_max - skip_count)); } SECTION("O_DIRECT") { fmt::print("O_DIRECT\n"); double total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rp"); { cucim::logger::Timer timer("- read whole : {:.7f}\n", true, false); fd->pread(aligned_host, test_file_size, 0); double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Read whole average: {}\n", total_elapsed_time / (iter_max - skip_count)); total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rp"); { cucim::logger::Timer timer("- read tiles : {:.7f}\n", true, false); for (uint32_t i = 0; i < image_piece_count_; ++i) { fd->pread(buffer_host, image_piece_bytecounts_[i], image_piece_offsets_[i]); } double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Read tiles average: {}\n", total_elapsed_time / (iter_max - skip_count)); } SECTION("O_DIRECT pre-load") { fmt::print("O_DIRECT pre-load\n"); size_t file_start_offset = ALIGN_DOWN(min_offset, BLOCK_SECTOR_SIZE); size_t end_boundary_offset = ALIGN_UP(max_offset + max_bytecount, BLOCK_SECTOR_SIZE); size_t large_block_size = end_boundary_offset - file_start_offset; fmt::print("- size:{}\n", end_boundary_offset - file_start_offset); double total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rp"); { cucim::logger::Timer timer("- preload : {:.7f}\n", true, false); fd->pread(aligned_host, large_block_size, file_start_offset); double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Preload average: {}\n", total_elapsed_time / (iter_max - skip_count)); total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd = cucim::filesystem::open(input_file.c_str(), "rp"); { cucim::logger::Timer timer("- read tiles : {:.7f}\n", true, false); for (uint32_t i = 0; i < image_piece_count_; ++i) { memcpy(buffer_host, aligned_host + image_piece_offsets_[i] - file_start_offset, image_piece_bytecounts_[i]); } double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- Read tiles average: {}\n", total_elapsed_time / (iter_max - skip_count)); } SECTION("mmap") { fmt::print("mmap\n"); double total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); auto fd_mmap = open(input_file.c_str(), O_RDONLY); { cucim::logger::Timer timer("- open/close : {:.7f}\n", true, false); void* mmap_host = mmap((void*)0, test_file_size, PROT_READ, MAP_SHARED, fd_mmap, 0); REQUIRE(mmap_host != MAP_FAILED); if (mmap_host != MAP_FAILED) { REQUIRE(munmap(mmap_host, test_file_size) != -1); close(fd_mmap); } double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } } fmt::print("- mmap/munmap average: {}\n", total_elapsed_time / (iter_max - skip_count)); total_elapsed_time = 0; for (int iter = 0; iter < iter_max; ++iter) { cucim::filesystem::discard_page_cache(input_file.c_str()); // auto fd_mmap = open(input_file, O_RDONLY); // void* mmap_host = mmap((void*)0, test_file_size, PROT_READ, MAP_SHARED, fd_mmap, 0); // REQUIRE(mmap_host != MAP_FAILED); auto fd = cucim::filesystem::open(input_file.c_str(), "rm"); { cucim::logger::Timer timer("- read tiles : {:.7f}\n", true, false); for (uint32_t i = 0; i < image_piece_count_; ++i) { // 3.441 => 3.489 fd->pread(buffer_host, image_piece_bytecounts_[i], image_piece_offsets_[i]); // memcpy(buffer_host, static_cast<char*>(mmap_host) + // image_piece_offsets_[i], image_piece_bytecounts_[i]); } double elapsed_time = timer.stop(); if (iter >= skip_count) { total_elapsed_time += elapsed_time; } timer.print(); } // if (mmap_host != MAP_FAILED) // { // REQUIRE(munmap(mmap_host, test_file_size) != -1); // } // close(fd_mmap); } fmt::print("- Read tiles average: {}\n", total_elapsed_time / (iter_max - skip_count)); } free(unaligned_host); free(buffer_host); }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/benchmarks/config.h
/* * Apache License, Version 2.0 * Copyright 2020-2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_CONFIG_H #define CUSLIDE_CONFIG_H #include <string> struct AppConfig { std::string test_folder; std::string test_file; bool discard_cache = false; int random_seed = 0; bool random_start_location = false; int64_t image_width = 0; int64_t image_height = 0; // Pseudo configurations for google benchmark bool benchmark_list_tests = false; std::string benchmark_filter; // <regex> int benchmark_min_time = 0; // <min_time> int benchmark_repetitions = 0; // <num_repetitions> bool benchmark_report_aggregates_only = false; bool benchmark_display_aggregates_only = false; std::string benchmark_format; // <console|json|csv> std::string benchmark_out; // <filename> std::string benchmark_out_format; // <json|console|csv> std::string benchmark_color; // {auto|true|false} std::string benchmark_counters_tabular; std::string v; // <verbosity> std::string get_input_path(const std::string default_value = "generated/tiff_stripe_4096x4096_256.tif") const { // If `test_file` is absolute path if (!test_folder.empty() && test_file.substr(0, 1) == "/") { return test_file; } else { std::string test_data_folder = test_folder; if (test_data_folder.empty()) { if (const char* env_p = std::getenv("CUCIM_TESTDATA_FOLDER")) { test_data_folder = env_p; } else { test_data_folder = "test_data"; } } if (test_file.empty()) { return test_data_folder + "/" + default_value; } else { return test_data_folder + "/" + test_file; } } } }; #endif // CUSLIDE_CONFIG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/benchmarks/CMakeLists.txt
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ # Add executable: cuslide_benchmarks ################################################################################ add_executable(cuslide_benchmarks main.cpp config.h) #set_source_files_properties(main.cpp PROPERTIES LANGUAGE CUDA) # failed with CLI11 library set_target_properties(cuslide_benchmarks PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES CXX_EXTENSIONS NO ) target_compile_features(cuslide_benchmarks PRIVATE ${CUCIM_REQUIRED_FEATURES}) # Use generator expression to avoid `nvcc fatal : Value '-std=c++17' is not defined for option 'Werror'` target_compile_options(cuslide_benchmarks PRIVATE $<$<COMPILE_LANGUAGE:CXX>:-Werror -Wall -Wextra>) target_compile_definitions(cuslide_benchmarks PUBLIC CUSLIDE_VERSION=${PROJECT_VERSION} CUSLIDE_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} CUSLIDE_VERSION_MINOR=${PROJECT_VERSION_MINOR} CUSLIDE_VERSION_PATCH=${PROJECT_VERSION_PATCH} CUSLIDE_VERSION_BUILD=${PROJECT_VERSION_BUILD} ) target_link_libraries(cuslide_benchmarks PRIVATE cucim::cucim deps::googlebenchmark deps::openslide deps::cli11 )
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/benchmarks/main.cpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <fcntl.h> #include <unistd.h> #include <cstdlib> #include <cstring> #include <benchmark/benchmark.h> #include <CLI/CLI.hpp> #include <fmt/format.h> #include <openslide/openslide.h> #include "cucim/core/framework.h" #include "cucim/io/format/image_format.h" #include "cucim/memory/memory_manager.h" #define XSTR(x) STR(x) #define STR(x) #x //#include <chrono> CUCIM_FRAMEWORK_GLOBALS("cuslide.app") static AppConfig g_config; static void test_basic(benchmark::State& state) { std::string input_path = g_config.get_input_path(); int arg = -1; for (auto state_item : state) { state.PauseTiming(); { // Use a different start random seed for the different argument if (arg != state.range()) { arg = state.range(); srand(g_config.random_seed + arg); } if (g_config.discard_cache) { int fd = open(input_path.c_str(), O_RDONLY); fdatasync(fd); posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); close(fd); } } state.ResumeTiming(); // auto start = std::chrono::high_resolution_clock::now(); cucim::Framework* framework = cucim::acquire_framework("cuslide.app"); if (!framework) { fmt::print("framework is not available!\n"); return; } cucim::io::format::IImageFormat* image_format = framework->acquire_interface_from_library<cucim::io::format::IImageFormat>( "cucim.kit.cuslide@" XSTR(CUSLIDE_VERSION) ".so"); // std::cout << image_format->formats[0].get_format_name() << std::endl; if (image_format == nullptr) { fmt::print("plugin library is not available!\n"); return; } std::string input_path = g_config.get_input_path(); std::shared_ptr<CuCIMFileHandle>* file_handle_shared = reinterpret_cast<std::shared_ptr<CuCIMFileHandle>*>( image_format->formats[0].image_parser.open(input_path.c_str())); std::shared_ptr<CuCIMFileHandle> file_handle = *file_handle_shared; delete file_handle_shared; // Set deleter to close the file handle file_handle->set_deleter(image_format->formats[0].image_parser.close); cucim::io::format::ImageMetadata metadata{}; image_format->formats[0].image_parser.parse(file_handle.get(), &metadata.desc()); cucim::io::format::ImageReaderRegionRequestDesc request{}; int64_t request_location[2] = { 0, 0 }; if (g_config.random_start_location) { request_location[0] = rand() % (g_config.image_width - state.range(0)); request_location[1] = rand() % (g_config.image_height - state.range(0)); } request.location = request_location; request.level = 0; int64_t request_size[2] = { state.range(0), state.range(0) }; request.size = request_size; request.device = const_cast<char*>("cpu"); cucim::io::format::ImageDataDesc image_data; image_format->formats[0].image_reader.read( file_handle.get(), &metadata.desc(), &request, &image_data, nullptr /*out_metadata*/); cucim_free(image_data.container.data); // auto end = std::chrono::high_resolution_clock::now(); // auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); // state.SetIterationTime(elapsed_seconds.count()); } } static void test_openslide(benchmark::State& state) { std::string input_path = g_config.get_input_path(); int arg = -1; for (auto _ : state) { state.PauseTiming(); { // Use a different start random seed for the different argument if (arg != state.range()) { arg = state.range(); srand(g_config.random_seed + arg); } if (g_config.discard_cache) { int fd = open(input_path.c_str(), O_RDONLY); fdatasync(fd); posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); close(fd); } } state.ResumeTiming(); openslide_t* slide = openslide_open(input_path.c_str()); uint32_t* buf = static_cast<uint32_t*>(cucim_malloc(state.range(0) * state.range(0) * 4)); int64_t request_location[2] = { 0, 0 }; if (g_config.random_start_location) { request_location[0] = rand() % (g_config.image_width - state.range(0)); request_location[1] = rand() % (g_config.image_height - state.range(0)); } openslide_read_region(slide, buf, request_location[0], request_location[1], 0, state.range(0), state.range(0)); cucim_free(buf); openslide_close(slide); } } BENCHMARK(test_basic)->Unit(benchmark::kMicrosecond)->RangeMultiplier(2)->Range(1, 4096); //->UseManualTime(); BENCHMARK(test_openslide)->Unit(benchmark::kMicrosecond)->RangeMultiplier(2)->Range(1, 4096); static bool remove_help_option(int* argc, char** argv) { for (int i = 1; argc && i < *argc; ++i) { if (strncmp(argv[i], "-h", 3) == 0 || strncmp(argv[i], "--help", 7) == 0) { for (int j = i + 1; argc && j < *argc; ++j) { argv[j - 1] = argv[j]; } --(*argc); argv[*argc] = nullptr; return true; } } return false; } static bool setup_configuration() { std::string input_path = g_config.get_input_path(); openslide_t* slide = openslide_open(input_path.c_str()); if (slide == nullptr) { fmt::print("[Error] Cannot load {}!\n", input_path); return false; } int64_t w, h; openslide_get_level0_dimensions(slide, &w, &h); g_config.image_width = w; g_config.image_height = h; openslide_close(slide); return true; } // BENCHMARK_MAIN(); int main(int argc, char** argv) { // Skip processing help option bool has_help_option = remove_help_option(&argc, argv); ::benchmark::Initialize(&argc, argv); // if (::benchmark::ReportUnrecognizedArguments(argc, argv)) // return 1; CLI::App app{ "benchmark: cuSlide" }; app.add_option("--test_folder", g_config.test_folder, "An input test folder path"); app.add_option("--test_file", g_config.test_file, "An input test image file path"); app.add_option("--discard_cache", g_config.discard_cache, "Discard page cache for the input file for each iteration"); app.add_option("--random_seed", g_config.random_seed, "A random seed number"); app.add_option( "--random_start_location", g_config.random_start_location, "Randomize start location of read_region()"); // Pseudo benchmark options app.add_option("--benchmark_list_tests", g_config.benchmark_list_tests, "{true|false}"); app.add_option("--benchmark_filter", g_config.benchmark_filter, "<regex>"); app.add_option("--benchmark_min_time", g_config.benchmark_min_time, "<min_time>"); app.add_option("--benchmark_repetitions", g_config.benchmark_repetitions, "<num_repetitions>"); app.add_option("--benchmark_report_aggregates_only", g_config.benchmark_report_aggregates_only, "{true|false}"); app.add_option("--benchmark_display_aggregates_only", g_config.benchmark_display_aggregates_only, "{true|false}"); app.add_option("--benchmark_format", g_config.benchmark_format, "<console|json|csv>"); app.add_option("--benchmark_out", g_config.benchmark_out, "<filename>"); app.add_option("--benchmark_out_format", g_config.benchmark_out_format, "<json|console|csv>"); app.add_option("--benchmark_color", g_config.benchmark_color, "{auto|true|false}"); app.add_option("--benchmark_counters_tabular", g_config.benchmark_counters_tabular, "{true|false}"); app.add_option("--v", g_config.v, "<verbosity>"); // Append help option if exists if (has_help_option) { argv[argc] = const_cast<char*>("--help"); ++argc; // https://github.com/matepek/vscode-catch2-test-adapter detects google benchmark binaries by the following // text: printf("benchmark [--benchmark_list_tests={true|false}]\n"); } CLI11_PARSE(app, argc, argv); if (!setup_configuration()) { return 1; } ::benchmark::RunSpecifiedBenchmarks(); }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/misc.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" /> <component name="JavaScriptSettings"> <option name="languageLevel" value="ES6" /> </component> </project>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/.name
cuslide
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/vcs.xml
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="$PROJECT_DIR$/../../.." vcs="Git" /> </component> </project>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/cucim.kit.cuslide.iml
<?xml version="1.0" encoding="UTF-8"?> <module classpath="CMake" type="CPP_MODULE" version="4" />
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/codeStyles/codeStyleConfig.xml
<component name="ProjectCodeStyleConfiguration"> <state> <option name="USE_PER_PROJECT_SETTINGS" value="true" /> </state> </component>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/codeStyles/Project.xml
<component name="ProjectCodeStyleConfiguration"> <code_scheme name="Project" version="173"> <clangFormatSettings> <option name="ENABLED" value="true" /> </clangFormatSettings> </code_scheme> </component>
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/includes/NVIDIA_CMAKE_HEADER.cmake
# # Copyright (c) $YEAR, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/includes/NVIDIA_C_HEADER.h
/* * Copyright (c) $YEAR, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/internal/CMakeLists.txt.cmake
#parse("NVIDIA_CMAKE_HEADER.cmake")
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/internal/C Header File.h
#parse("NVIDIA_C_HEADER.h") #[[#ifndef]]# ${INCLUDE_GUARD} #[[#define]]# ${INCLUDE_GUARD} #[[#endif]]# //${INCLUDE_GUARD}
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/internal/C++ Class.cc
#parse("NVIDIA_C_HEADER.h") #[[#include]]# "${HEADER_FILENAME}"
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/internal/C Source File.c
#parse("NVIDIA_C_HEADER.h") #if (${HEADER_FILENAME}) #[[#include]]# "${HEADER_FILENAME}" #end
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/.idea/fileTemplates/internal/C++ Class Header.h
#parse("NVIDIA_C_HEADER.h") #[[#ifndef]]# ${INCLUDE_GUARD} #[[#define]]# ${INCLUDE_GUARD} ${NAMESPACES_OPEN} class ${NAME} { }; ${NAMESPACES_CLOSE} #[[#endif]]# //${INCLUDE_GUARD}
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/cucim.kit.cuslide-config.cmake.in
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @PACKAGE_INIT@ # Find dependent libraries # ... include(CMakeFindDependencyMacro) #find_dependency(Boost x.x.x REQUIRED) if(NOT TARGET cuslide::cuslide) include(${CMAKE_CURRENT_LIST_DIR}/cucim.kit.cuslide-targets.cmake) endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/modules/CuCIMUtils.cmake
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Store current BUILD_SHARED_LIBS setting in CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_set_build_shared_libs) macro(cucim_set_build_shared_libs new_value) set(CUCIM_OLD_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}}) if (DEFINED CACHE{BUILD_SHARED_LIBS}) set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED TRUE) else() set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED FALSE) endif() set(BUILD_SHARED_LIBS ${new_value} CACHE BOOL "" FORCE) endmacro() endif() # Restore BUILD_SHARED_LIBS setting from CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_restore_build_shared_libs) macro(cucim_restore_build_shared_libs) if (CUCIM_OLD_BUILD_SHARED_LIBS_CACHED) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS} CACHE BOOL "" FORCE) else() unset(BUILD_SHARED_LIBS CACHE) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS}) endif() endmacro() endif() # Define CMAKE_CUDA_ARCHITECTURES for the given architecture values # # Params: # arch_list - architecture value list (e.g., '60;70;75;80;86') if(NOT COMMAND cucim_define_cuda_architectures) function(cucim_define_cuda_architectures arch_list) set(arch_string "") # Create SASS for all architectures in the list foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${arch}-real") endforeach(arch) # Create PTX for the latest architecture for forward-compatibility. list(GET arch_list -1 latest_arch) foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${latest_arch}-virtual") endforeach(arch) set(CMAKE_CUDA_ARCHITECTURES ${arch_string} PARENT_SCOPE) endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/modules/SuperBuildUtils.cmake
# Apache License, Version 2.0 # Copyright 2020 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. include(FetchContent) set(CMAKE_SUPERBUILD_DEPS_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/..") if(NOT COMMAND superbuild_depend) function(superbuild_depend module_name) include("${CMAKE_SUPERBUILD_DEPS_ROOT_DIR}/deps/${module_name}.cmake") endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/json.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::json) FetchContent_Declare( deps-json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.9.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-json) if (NOT deps-json_POPULATED) message(STATUS "Fetching json sources") FetchContent_Populate(deps-json) message(STATUS "Fetching json sources - done") endif () # Typically you don't care so much for a third party library's tests to be # run from your own project's code. set(JSON_BuildTests OFF CACHE INTERNAL "") add_subdirectory(${deps-json_SOURCE_DIR} ${deps-json_BINARY_DIR} EXCLUDE_FROM_ALL) add_library(deps::json INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::json INTERFACE nlohmann_json::nlohmann_json) set(deps-json_SOURCE_DIR ${deps-json_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-json_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libtiff-policies-fix.cmake
# Apache License, Version 2.0 # Copyright 2020 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The following cmake policies are set by `CMAKE_PROJECT_INCLUDE_BEFORE` variables # when `FetchContent` command is used (see https://gitlab.kitware.com/cmake/cmake/-/issues/19854). cmake_policy(SET CMP0072 NEW) # FindOpenGL prefers GLVND by default when available. for libtiff cmake_policy(SET CMP0048 NEW) # project() command manages VERSION variables. for libtiff cmake_policy(SET CMP0063 NEW) # Honor the visibility properties for all target types including static library. cmake_policy(SET CMP0077 NEW) # Honor normal variables. Without this, `set(jpeg OFF)` trick to force using static libjpeg-turbo doesn't work.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/nvjpeg.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::nvjpeg_static) add_library(deps::nvjpeg_static STATIC IMPORTED GLOBAL) if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../../../temp/cuda/include/nvjpeg.h) set(NVJPEG_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../temp/cuda/include) else () message(FATAL_ERROR "nvjpeg.h not found") endif () message("Set NVJPEG_INCLUDE_PATH to '${NVJPEG_INCLUDE_PATH}'.") if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/../../../temp/cuda/lib64/libnvjpeg_static.a) set(NVJPEG_STATIC_LIB_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../temp/cuda/lib64/libnvjpeg_static.a) else () message(FATAL_ERROR "libnvjpeg_static.a not found") endif () message("Set NVJPEG_STATIC_LIB_PATH to '${NVJPEG_STATIC_LIB_PATH}'.") set_target_properties(deps::nvjpeg_static PROPERTIES IMPORTED_LOCATION "${NVJPEG_STATIC_LIB_PATH}" INTERFACE_INCLUDE_DIRECTORIES "${NVJPEG_INCLUDE_PATH}" ) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/boost.cmake
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::boost) set(Boost_VERSION 1.75.0) set(Boost_BUILD_COMPONENTS container) set(Boost_BUILD_OPTIONS "threading=multi cxxflags=-fPIC runtime-link=static variant=release link=static address-model=64 --layout=system") set(Boost_COMPILE_DEFINITIONS BOOST_COROUTINES_NO_DEPRECATION_WARNING=1 BOOST_ALL_NO_LIB=1 BOOST_UUID_RANDOM_PROVIDER_FORCE_WINCRYPT=1 CACHE INTERNAL "Boost compile definitions") set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME ON) foreach(component_name ${Boost_BUILD_COMPONENTS}) list(APPEND Boost_BUILD_VARIANTS --with-${component_name}) endforeach() FetchContent_Declare( deps-boost GIT_REPOSITORY https://github.com/boostorg/boost.git GIT_TAG boost-${Boost_VERSION} GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-boost) if (NOT deps-boost_POPULATED) message(STATUS "Fetching boost sources") FetchContent_Populate(deps-boost) message(STATUS "Fetching boost sources - done") endif () if (deps-boost_POPULATED AND NOT EXISTS "${deps-boost_BINARY_DIR}/install") include(ProcessorCount) ProcessorCount(PROCESSOR_COUNT) execute_process(COMMAND /bin/bash -c "./bootstrap.sh --prefix=${deps-boost_BINARY_DIR}/install && ./b2 install --build-dir=${deps-boost_BINARY_DIR}/build --stagedir=${deps-boost_BINARY_DIR}/stage -j${PROCESSOR_COUNT} ${Boost_BUILD_VARIANTS} ${Boost_BUILD_OPTIONS}" WORKING_DIRECTORY ${deps-boost_SOURCE_DIR} COMMAND_ECHO STDOUT RESULT_VARIABLE Boost_BUILD_RESULT) if(NOT Boost_BUILD_RESULT EQUAL "0") message(FATAL_ERROR "boost library build failed with ${Boost_BUILD_RESULT}, please checkout the boost module configurations") endif() endif() find_package(Boost 1.75 CONFIG REQUIRED COMPONENTS ${Boost_BUILD_COMPONENTS} HINTS ${deps-boost_BINARY_DIR}/install) # /lib/cmake/Boost-${Boost_VERSION} message(STATUS "Boost version: ${Boost_VERSION}") add_library(deps::boost INTERFACE IMPORTED GLOBAL) set_target_properties(deps::boost PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${Boost_INCLUDE_DIRS}" INTERFACE_COMPILE_DEFINITIONS "${Boost_COMPILE_DEFINITIONS}" INTERFACE_LINK_LIBRARIES "${Boost_LIBRARIES}" ) set(deps-boost_SOURCE_DIR ${deps-boost_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-boost_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libculibos.cmake
# # Copyright (c) 2022, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This module tries to find libculibos.a from /usr/local/cuda if # CUDA::culibos is not available through `find_package(CUDAToolkit REQUIRED)`. if (NOT TARGET CUDA::culibos) find_package(CUDAToolkit REQUIRED) if(NOT TARGET CUDA::culibos) find_library(CUDA_culibos_LIBRARY NAMES culibos HINTS /usr/local/cuda ENV CUDA_PATH PATH_SUFFIXES nvidia/current lib64 lib/x64 lib ) mark_as_advanced(CUDA_culibos_LIBRARY) if (NOT TARGET CUDA::culibos AND CUDA_culibos_LIBRARY) add_library(CUDA::culibos STATIC IMPORTED GLOBAL) target_include_directories(CUDA::culibos SYSTEM INTERFACE "${CUDAToolkit_INCLUDE_DIRS}") set_property(TARGET CUDA::culibos PROPERTY IMPORTED_LOCATION "${CUDA_culibos_LIBRARY}") message("Set CUDA_culibos_LIBRARY to '${CUDA_culibos_LIBRARY}'.") else () message(FATAL_ERROR "Could not find CUDA::culibos.") endif() endif () endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libjpeg-turbo-policies-fix.cmake
# Apache License, Version 2.0 # Copyright 2020-2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The following cmake policies are set by `CMAKE_PROJECT_INCLUDE_BEFORE` variables # when `FetchContent` command is used (see https://gitlab.kitware.com/cmake/cmake/-/issues/19854). cmake_policy(SET CMP0048 NEW) # project() command manages VERSION variables. for libjpeg-turbo cmake_policy(SET CMP0054 NEW) # cmake-build-debug/_deps/deps-libjpeg-turbo-src/cmakescripts/GNUInstallDirs.cmake:174 (elseif): cmake_policy(SET CMP0063 NEW) # Honor the visibility properties for all target types including static library. cmake_policy(SET CMP0077 NEW) # Use normal variable that is injected, instead of ignoring/clearing normal variable: REQUIRE_SIMD/CMAKE_ASM_NASM_COMPILER. # https://cmake.org/cmake/help/v3.18/policy/CMP0065.html : Do not add flags to export symbols from executables without the ENABLE_EXPORTS target property. # : this policy is not handled yet so always enable exports.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/catch2.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::catch2) FetchContent_Declare( deps-catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.4.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-catch2) if (NOT deps-catch2_POPULATED) message(STATUS "Fetching catch2 sources") FetchContent_Populate(deps-catch2) message(STATUS "Fetching catch2 sources - done") endif () add_subdirectory(${deps-catch2_SOURCE_DIR} ${deps-catch2_BINARY_DIR} EXCLUDE_FROM_ALL) # Include Append catch2's cmake module path so that we can use `include(Catch)`. # https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake list(APPEND CMAKE_MODULE_PATH "${deps-catch2_SOURCE_DIR}/extras") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} PARENT_SCOPE) add_library(deps::catch2 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::catch2 INTERFACE Catch2::Catch2) set(deps-catch2_SOURCE_DIR ${deps-catch2_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-catch2_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/pugixml.cmake
# Apache License, Version 2.0 # Copyright 2020 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::pugixml) FetchContent_Declare( deps-pugixml GIT_REPOSITORY https://github.com/zeux/pugixml.git GIT_TAG v1.11.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-pugixml) if (NOT deps-pugixml_POPULATED) message(STATUS "Fetching pugixml sources") FetchContent_Populate(deps-pugixml) message(STATUS "Fetching pugixml sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-pugixml_SOURCE_DIR} ${deps-pugixml_BINARY_DIR} EXCLUDE_FROM_ALL) # Disable visibility to not expose unnecessary symbols set_target_properties(pugixml-static PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES) cucim_restore_build_shared_libs() add_library(deps::pugixml INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::pugixml INTERFACE pugixml-static) set(deps-pugixml_SOURCE_DIR ${deps-pugixml_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-pugixml_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/googletest.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googletest) FetchContent_Declare( deps-googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.10.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googletest) if (NOT deps-googletest_POPULATED) message(STATUS "Fetching googletest sources") FetchContent_Populate(deps-googletest) message(STATUS "Fetching googletest sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-googletest_SOURCE_DIR} ${deps-googletest_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googletest INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googletest INTERFACE googletest) set(deps-googletest_SOURCE_DIR ${deps-googletest_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googletest_SOURCE_DIR) endif () #CMake Warning (dev) in cmake-build-debug/_deps/deps-googletest-src/googlemock/CMakeLists.txt: # Policy CMP0082 is not set: Install rules from add_subdirectory() are # interleaved with those in caller. Run "cmake --help-policy CMP0082" for # policy details. Use the cmake_policy command to set the policy and # suppress this warning.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/openslide.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::openslide) add_library(deps::openslide SHARED IMPORTED GLOBAL) if (DEFINED ENV{CONDA_BUILD}) set(OPENSLIDE_LIB_PATH "$ENV{PREFIX}/lib/libopenslide.so") elseif (DEFINED ENV{CONDA_PREFIX}) set(OPENSLIDE_LIB_PATH "$ENV{CONDA_PREFIX}/lib/libopenslide.so") elseif (EXISTS /usr/lib/x86_64-linux-gnu/libopenslide.so) set(OPENSLIDE_LIB_PATH /usr/lib/x86_64-linux-gnu/libopenslide.so) elseif (EXISTS /usr/lib/aarch64-linux-gnu/libopenslide.so) set(OPENSLIDE_LIB_PATH /usr/lib/aarch64-linux-gnu/libopenslide.so) else () # CentOS (x86_64) set(OPENSLIDE_LIB_PATH /usr/lib64/libopenslide.so) endif () if (DEFINED ENV{CONDA_BUILD}) set(OPENSLIDE_INCLUDE_PATH "$ENV{PREFIX}/include/") elseif (DEFINED ENV{CONDA_PREFIX}) set(OPENSLIDE_INCLUDE_PATH "$ENV{CONDA_PREFIX}/include/") else () set(OPENSLIDE_INCLUDE_PATH "/usr/include/") endif () set_target_properties(deps::openslide PROPERTIES IMPORTED_LOCATION "${OPENSLIDE_LIB_PATH}" INTERFACE_INCLUDE_DIRECTORIES "${OPENSLIDE_INCLUDE_PATH}" ) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/cli11.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::cli11) FetchContent_Declare( deps-cli11 GIT_REPOSITORY https://github.com/CLIUtils/CLI11.git GIT_TAG v1.9.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-cli11) if (NOT deps-cli11_POPULATED) message(STATUS "Fetching cli11 sources") FetchContent_Populate(deps-cli11) message(STATUS "Fetching cli11 sources - done") endif () add_subdirectory(${deps-cli11_SOURCE_DIR} ${deps-cli11_BINARY_DIR} EXCLUDE_FROM_ALL) add_library(deps::cli11 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::cli11 INTERFACE CLI11::CLI11) set(deps-cli11_SOURCE_DIR ${deps-cli11_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-cli11_SOURCE_DIR) endif () # Note that library had a failure with nvcc compiler and gcc 9.x headers # ...c++/9/tuple(553): error: pack "_UElements" does not have the same number of elements as "_Elements" # __and_<is_nothrow_assignable<_Elements&, _UElements>...>::value; # Not using nvcc for main code that uses cli11 solved the issue.
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libopenjpeg.cmake
# Apache License, Version 2.0 # Copyright 2020-2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::libopenjpeg) FetchContent_Declare( deps-libopenjpeg GIT_REPOSITORY https://github.com/uclouvain/openjpeg.git GIT_TAG v2.4.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-libopenjpeg) if (NOT deps-libopenjpeg_POPULATED) message(STATUS "Fetching libopenjpeg sources") FetchContent_Populate(deps-libopenjpeg) message(STATUS "Fetching libopenjpeg sources - done") endif () # Create static library # It build a static library when both BUILD_SHARED_LIBS and BUILD_STATIC_LIBS are ON # (build-debug/_deps/deps-libopenjpeg-src/src/lib/openjp2/CMakeLists.txt:94) # # if(BUILD_SHARED_LIBS AND BUILD_STATIC_LIBS) cucim_set_build_shared_libs(ON) ########################################################################### # Build liblcms2 with the source in libopenjpeg ########################################################################### add_subdirectory(${deps-libopenjpeg_SOURCE_DIR}/thirdparty/liblcms2 ${deps-libopenjpeg_BINARY_DIR}/thirdparty/liblcms2) # Override the output library folder path set_target_properties(lcms2 PROPERTIES OUTPUT_NAME "lcms2" ARCHIVE_OUTPUT_DIRECTORY ${deps-libopenjpeg_BINARY_DIR}/thirdparty/lib) # Override definition of OPJ_HAVE_LIBLCMS2 to build color_apply_icc_profile() method target_compile_definitions(lcms2 PUBLIC OPJ_HAVE_LIBLCMS2=1 ) # Set PIC to prevent the following error message # : /usr/bin/ld: _deps/deps-libopenjpeg-build/thirdparty/lib/liblcms2.a(cmserr.c.o): relocation R_X86_64_PC32 against symbol `_cmsMemPluginChunk' can not be used when making a shared object; recompile with -fPIC # /usr/bin/ld: final link failed: bad value set_target_properties(lcms2 PROPERTIES POSITION_INDEPENDENT_CODE ON) add_library(deps::libopenjpeg-lcms2 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::libopenjpeg-lcms2 INTERFACE lcms2) target_include_directories(deps::libopenjpeg-lcms2 INTERFACE # lcms2.h is not included in 'lcms2' so manually include ${deps-libopenjpeg_SOURCE_DIR}/thirdparty/liblcms2/include ) set(deps-libopenjpeg-lcms2_SOURCE_DIR ${deps-libopenjpeg_SOURCE_DIR}/thirdparty/liblcms2 CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libopenjpeg-lcms2_SOURCE_DIR) set(deps-libopenjpeg-lcms2_BINARY_DIR ${deps-libopenjpeg_BINARY_DIR}/thirdparty/liblcms2 CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libopenjpeg-lcms2_BINARY_DIR) ########################################################################### add_subdirectory(${deps-libopenjpeg_SOURCE_DIR} ${deps-libopenjpeg_BINARY_DIR} EXCLUDE_FROM_ALL) # Disable visibility to not expose unnecessary symbols set_target_properties(openjp2_static PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES ) # target_compile_options(openjp2_static PRIVATE $<$<CXX_COMPILER_ID:GNU>:-march=core-avx2>) # Set PIC to prevent the following error message # : /usr/bin/ld: lib/libopenjp2.a(cio.c.o): relocation R_X86_64_PC32 against symbol `opj_stream_read_skip' can not be used when making a shared object; recompile with -fPIC # /usr/bin/ld: final link failed: bad value set_target_properties(openjp2_static PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::libopenjpeg INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::libopenjpeg INTERFACE openjp2_static) target_include_directories(deps::libopenjpeg INTERFACE # openjpeg.h is not included in 'openjp2_static' so manually include ${deps-libopenjpeg_SOURCE_DIR}/src/lib/openjp2 # opj_config.h is not included in openjp2_static so manually include ${deps-libopenjpeg_BINARY_DIR}/src/lib/openjp2 # color.h is not included in 'openjp2_static' so manually include ${deps-libopenjpeg_SOURCE_DIR}/src/bin/common # opj_apps_config.h is not included in 'openjp2_static' so manually include ${deps-libopenjpeg_BINARY_DIR}/src/bin/common ) set(deps-libopenjpeg_SOURCE_DIR ${deps-libopenjpeg_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libopenjpeg_SOURCE_DIR) set(deps-libopenjpeg_BINARY_DIR ${deps-libopenjpeg_BINARY_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libopenjpeg_BINARY_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libjpeg-turbo.cmake
# Apache License, Version 2.0 # Copyright 2020-2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::libjpeg-turbo) # add_library(deps::libjpeg-turbo SHARED IMPORTED GLOBAL) # # set_target_properties(deps::libjpeg-turbo PROPERTIES # IMPORTED_LOCATION "/usr/lib/x86_64-linux-gnu/libjpeg-turbo.so" # INTERFACE_INCLUDE_DIRECTORIES "/usr/include/x86_64-linux-gnu" # ) FetchContent_Declare( deps-libjpeg-turbo GIT_REPOSITORY https://github.com/libjpeg-turbo/libjpeg-turbo.git GIT_TAG 2.0.6 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-libjpeg-turbo) if (NOT deps-libjpeg-turbo_POPULATED) message(STATUS "Fetching libjpeg-turbo sources") FetchContent_Populate(deps-libjpeg-turbo) message(STATUS "Fetching libjpeg-turbo sources - done") endif () # Set policies for libjpeg-turbo set(CMAKE_PROJECT_INCLUDE_BEFORE "${CMAKE_CURRENT_LIST_DIR}/libjpeg-turbo-policies-fix.cmake") # Create static library cucim_set_build_shared_libs(OFF) # Tell CMake where to find the compiler by setting either the environment # variable "ASM_NASM" or the CMake cache entry CMAKE_ASM_NASM_COMPILER to the # full path to the compiler, or to the compiler name if it is in the PATH. # yasm is available through `sudo apt-get install yasm` on Debian Linux. # See _deps/deps-libjpeg-turbo-src/simd/CMakeLists.txt:25. set(CMAKE_ASM_NASM_COMPILER yasm) set(REQUIRE_SIMD 1) # CMP0077 add_subdirectory(${deps-libjpeg-turbo_SOURCE_DIR} ${deps-libjpeg-turbo_BINARY_DIR} EXCLUDE_FROM_ALL) # Disable visibility to not expose unnecessary symbols set_target_properties(turbojpeg-static PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES) # Set PIC to prevent the following error message # : /usr/bin/ld: lib/libturbojpeg.a(turbojpeg.c.o): relocation R_X86_64_TPOFF32 against `errStr' can not be used when making a shared object; recompile with -fPIC # /usr/bin/ld: final link failed: Nonrepresentable section on output set_target_properties(turbojpeg-static PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::libjpeg-turbo INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::libjpeg-turbo INTERFACE turbojpeg-static) target_include_directories(deps::libjpeg-turbo INTERFACE # turbojpeg.h is not included in 'turbojpeg-static' so manually include ${deps-libjpeg-turbo_SOURCE_DIR} ) set(deps-libjpeg-turbo_SOURCE_DIR ${deps-libjpeg-turbo_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libjpeg-turbo_SOURCE_DIR) set(deps-libjpeg-turbo_BINARY_DIR ${deps-libjpeg-turbo_BINARY_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libjpeg-turbo_BINARY_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/googlebenchmark.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googlebenchmark) FetchContent_Declare( deps-googlebenchmark GIT_REPOSITORY https://github.com/google/benchmark.git GIT_TAG v1.5.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googlebenchmark) if (NOT deps-googlebenchmark_POPULATED) message(STATUS "Fetching googlebenchmark sources") FetchContent_Populate(deps-googlebenchmark) message(STATUS "Fetching googlebenchmark sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) set(BENCHMARK_ENABLE_GTEST_TESTS OFF) add_subdirectory(${deps-googlebenchmark_SOURCE_DIR} ${deps-googlebenchmark_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googlebenchmark INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googlebenchmark INTERFACE benchmark::benchmark) set(deps-googlebenchmark_SOURCE_DIR ${deps-googlebenchmark_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googlebenchmark_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/fmt.cmake
# Apache License, Version 2.0 # Copyright 2020 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::fmt) FetchContent_Declare( deps-fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 7.0.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-fmt) if (NOT deps-fmt_POPULATED) message(STATUS "Fetching fmt sources") FetchContent_Populate(deps-fmt) message(STATUS "Fetching fmt sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-fmt_SOURCE_DIR} ${deps-fmt_BINARY_DIR} EXCLUDE_FROM_ALL) # Set PIC to prevent the following error message # : /usr/bin/ld: ../lib/libfmtd.a(format.cc.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC set_target_properties(fmt PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::fmt INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::fmt INTERFACE fmt::fmt-header-only) set(deps-fmt_SOURCE_DIR ${deps-fmt_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-fmt_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libdeflate.cmake
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::libdeflate) FetchContent_Declare( deps-libdeflate GIT_REPOSITORY https://github.com/ebiggers/libdeflate.git GIT_TAG v1.7 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-libdeflate) if (NOT deps-libdeflate_POPULATED) message(STATUS "Fetching libdeflate sources") FetchContent_Populate(deps-libdeflate) message(STATUS "Fetching libdeflate sources - done") endif () if (deps-libdeflate_POPULATED AND NOT EXISTS "${deps-libdeflate_BINARY_DIR}/install") include(ProcessorCount) ProcessorCount(PROCESSOR_COUNT) # /opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: _deps/deps-libdeflate-build/install/lib/libdeflate.a(deflate_decompress.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC if (CMAKE_BUILD_TYPE STREQUAL "Debug") set(LIBDEFLATE_CMAKE_ARGS "-e CFLAGS='-O0 -g3 -fPIC'") else() set(LIBDEFLATE_CMAKE_ARGS "-e CFLAGS='-fPIC'") endif() execute_process(COMMAND /bin/bash -c "make -e PREFIX=${deps-libdeflate_BINARY_DIR}/install ${LIBDEFLATE_CMAKE_ARGS} install -j${PROCESSOR_COUNT}" WORKING_DIRECTORY ${deps-libdeflate_SOURCE_DIR} COMMAND_ECHO STDOUT RESULT_VARIABLE libdeflate_BUILD_RESULT) if(NOT libdeflate_BUILD_RESULT EQUAL "0") message(FATAL_ERROR "libdeflate library build failed with ${libdeflate_BUILD_RESULT}, please checkout the configurations") endif() endif() add_library(deps::libdeflate INTERFACE IMPORTED GLOBAL) set_target_properties(deps::libdeflate PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${deps-libdeflate_BINARY_DIR}/install/include" INTERFACE_LINK_LIBRARIES "${deps-libdeflate_BINARY_DIR}/install/lib/libdeflate.a" ) set(deps-libdeflate_SOURCE_DIR ${deps-libdeflate_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libdeflate_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/cmake/deps/libtiff.cmake
# Apache License, Version 2.0 # Copyright 2020 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if (NOT TARGET deps::libtiff) # add_library(deps::libtiff SHARED IMPORTED GLOBAL) # # set_target_properties(deps::libtiff PROPERTIES # IMPORTED_LOCATION "/usr/lib/x86_64-linux-gnu/libtiff.so" # INTERFACE_INCLUDE_DIRECTORIES "/usr/include/x86_64-linux-gnu" # ) FetchContent_Declare( deps-libtiff GIT_REPOSITORY https://gitlab.com/libtiff/libtiff.git GIT_TAG v4.1.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-libtiff) if (NOT deps-libtiff_POPULATED) message(STATUS "Fetching libtiff sources") FetchContent_Populate(deps-libtiff) message(STATUS "Fetching libtiff sources - done") endif () # Set policies for libtiff set(CMAKE_PROJECT_INCLUDE_BEFORE "${CMAKE_CURRENT_LIST_DIR}/libtiff-policies-fix.cmake") # Create static library cucim_set_build_shared_libs(OFF) # The following does some tricks so that libtiff uses libjpeg-turbo instead of system's libjpeg. # - set jpeg to OFF so that we can manually specify LIBRARIES and INCLUDES # (status message in cmake shows jpeg is OFF but it actually use libjpeg) # - set TIFF_INCLUDES instead of JPEG_INCLUDE_DIR to set libjpeg-turbo's include folder with higher priority # (otherwise, jpeg's include dir wouldn't be the first of TIFF_INCLUDES) # Otherwise, libtiff would use system's shared libjpeg(8.0) whereas libjpeg turbo uses static libjpeg(6.2) # so symbol conflict(such as jpeg_CreateDecompress) happens. # See 'cmake-build-debug/_deps/deps-libtiff-src/CMakeLists.txt' for existing libtiff's logic. set(jpeg OFF) set(JPEG_FOUND TRUE) set(JPEG_LIBRARIES deps::libjpeg-turbo) # for jpeglib.h and jconfig.h/jconfigint.h set(TIFF_INCLUDES ${deps-libjpeg-turbo_SOURCE_DIR} ${deps-libjpeg-turbo_BINARY_DIR} ) add_subdirectory(${deps-libtiff_SOURCE_DIR} ${deps-libtiff_BINARY_DIR} EXCLUDE_FROM_ALL) # Disable visibility to not expose unnecessary symbols set_target_properties(tiff tiffxx PROPERTIES C_VISIBILITY_PRESET hidden CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES) # Set PIC to prevent the following error message # : /usr/bin/ld: lib/libtiff.a(tif_close.c.o): relocation R_X86_64_PC32 against symbol `TIFFCleanup' can not be used when making a shared object; recompile with -fPIC set_target_properties(tiff PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::libtiff INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::libtiff INTERFACE tiffxx) set(deps-libtiff_SOURCE_DIR ${deps-libtiff_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-libtiff_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/srctest.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_SRCTEST_H #define CUSLIDE_SRCTEST_H #endif // CUSLIDE_SRCTEST_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/cuslide.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_CUSLIDE_H #define CUSLIDE_CUSLIDE_H #endif // CUSLIDE_CUSLIDE_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/cuslide.cpp
/* * Copyright (c) 2020-2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define CUCIM_EXPORTS #include "cuslide.h" #include "cucim/core/framework.h" #include "cucim/core/plugin_util.h" #include "cucim/io/format/image_format.h" #include "tiff/tiff.h" #include <fmt/format.h> #include <nlohmann/json.hpp> #include <array> #include <cassert> #include <cstring> #include <fcntl.h> #include <filesystem> #include <memory> using json = nlohmann::json; const struct cucim::PluginImplDesc kPluginImpl = { "cucim.kit.cuslide", // name { 0, 1, 0 }, // version "dev", // build "clara team", // author "cuslide", // description "cuslide plugin", // long_description "Apache-2.0", // license "https://github.com/rapidsai/cucim", // url "linux", // platforms, cucim::PluginHotReload::kDisabled, // hot_reload }; // Using CARB_PLUGIN_IMPL_MINIMAL instead of CARB_PLUGIN_IMPL // This minimal macro doesn't define global variables for logging, profiler, crash reporting, // and also doesn't call for the client registration for those systems CUCIM_PLUGIN_IMPL_MINIMAL(kPluginImpl, cucim::io::format::IImageFormat) CUCIM_PLUGIN_IMPL_NO_DEPS() static void set_enabled(bool val) { (void)val; } static bool is_enabled() { return true; } static const char* get_format_name() { return "Generic TIFF"; } static bool CUCIM_ABI checker_is_valid(const char* file_name, const char* buf, size_t size) { (void)buf; (void)size; auto file = std::filesystem::path(file_name); auto extension = file.extension().string(); if (extension.compare(".tif") == 0 || extension.compare(".tiff") == 0 || extension.compare(".svs") == 0) { return true; } return false; } static CuCIMFileHandle_share CUCIM_ABI parser_open(const char* file_path) { auto tif = new cuslide::tiff::TIFF(file_path, O_RDONLY); tif->construct_ifds(); // Move the ownership of the file handle object to the caller (CuImage). auto handle_t = tif->file_handle(); tif->file_handle() = nullptr; CuCIMFileHandle_share handle = new std::shared_ptr<CuCIMFileHandle>(handle_t); return handle; } static bool CUCIM_ABI parser_parse(CuCIMFileHandle_ptr handle_ptr, cucim::io::format::ImageMetadataDesc* out_metadata_desc) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); if (!out_metadata_desc || !out_metadata_desc->handle) { throw std::runtime_error("out_metadata_desc shouldn't be nullptr!"); } cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data); size_t ifd_count = tif->ifd_count(); size_t level_count = tif->level_count(); // If not Aperio SVS format (== Ordinary Pyramid TIFF image) if (tif->ifd(0)->image_description().rfind("Aperio", 0) != 0) { std::vector<size_t> main_ifd_list; for (size_t i = 0; i < ifd_count; i++) { const std::shared_ptr<cuslide::tiff::IFD>& ifd = tif->ifd(i); uint64_t subfile_type = ifd->subfile_type(); if (subfile_type == 0) { main_ifd_list.push_back(i); } } // Assume that the image has only one main (high resolution) image. if (main_ifd_list.size() != 1) { throw std::runtime_error( fmt::format("This format has more than one image with Subfile Type 0 so cannot be loaded!")); } } // // Metadata Setup // // Note: int-> uint16_t due to type differences between ImageMetadataDesc.ndim and DLTensor.ndim const uint16_t ndim = 3; auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; const auto& level0_ifd = tif->level_ifd(0); std::pmr::vector<int64_t> shape( { level0_ifd->height(), level0_ifd->width(), level0_ifd->samples_per_pixel() }, &resource); DLDataType dtype{ kDLUInt, 8, 1 }; // TODO: Fill correct values for cucim::io::format::ImageMetadataDesc uint8_t n_ch = level0_ifd->samples_per_pixel(); if (n_ch != 3) { // Image loaded by a slow-path(libtiff) always will have 4 channel // (by TIFFRGBAImageGet() method in libtiff) n_ch = 4; shape[2] = 4; } std::pmr::vector<std::string_view> channel_names(&resource); channel_names.reserve(n_ch); if (n_ch == 3) { channel_names.emplace_back(std::string_view{ "R" }); channel_names.emplace_back(std::string_view{ "G" }); channel_names.emplace_back(std::string_view{ "B" }); } else { channel_names.emplace_back(std::string_view{ "R" }); channel_names.emplace_back(std::string_view{ "G" }); channel_names.emplace_back(std::string_view{ "B" }); channel_names.emplace_back(std::string_view{ "A" }); } // Spacing units std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); const auto resolution_unit = level0_ifd->resolution_unit(); const auto x_resolution = level0_ifd->x_resolution(); const auto y_resolution = level0_ifd->y_resolution(); switch (resolution_unit) { case 1: // no absolute unit of measurement spacing.emplace_back(y_resolution); spacing.emplace_back(x_resolution); spacing.emplace_back(1.0f); spacing_units.emplace_back(std::string_view{ "" }); spacing_units.emplace_back(std::string_view{ "" }); break; case 2: // inch spacing.emplace_back(y_resolution != 0 ? 25400 / y_resolution : 1.0f); spacing.emplace_back(x_resolution != 0 ? 25400 / x_resolution : 1.0f); spacing.emplace_back(1.0f); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "micrometer" }); break; case 3: // centimeter spacing.emplace_back(y_resolution != 0 ? 10000 / y_resolution : 1.0f); spacing.emplace_back(x_resolution != 0 ? 10000 / x_resolution : 1.0f); spacing.emplace_back(1.0f); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "micrometer" }); break; default: spacing.insert(spacing.end(), ndim, 1.0f); } spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; const uint16_t level_ndim = 2; std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { const auto& level_ifd = tif->level_ifd(i); level_dimensions.emplace_back(level_ifd->width()); level_dimensions.emplace_back(level_ifd->height()); } std::pmr::vector<float> level_downsamples(&resource); float orig_width = static_cast<float>(shape[1]); float orig_height = static_cast<float>(shape[0]); for (size_t i = 0; i < level_count; ++i) { const auto& level_ifd = tif->level_ifd(i); level_downsamples.emplace_back(((orig_width / level_ifd->width()) + (orig_height / level_ifd->height())) / 2); } std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_count * 2); for (size_t i = 0; i < level_count; ++i) { const auto& level_ifd = tif->level_ifd(i); level_tile_sizes.emplace_back(level_ifd->tile_width()); level_tile_sizes.emplace_back(level_ifd->tile_height()); } const size_t associated_image_count = tif->associated_image_count(); std::pmr::vector<std::string_view> associated_image_names(&resource); for (const auto& associated_image : tif->associated_images()) { associated_image_names.emplace_back(std::string_view{ associated_image.first.c_str() }); } auto& image_description = level0_ifd->image_description(); std::string_view raw_data{ image_description.empty() ? "" : image_description.c_str() }; // Dynamically allocate memory for json_data (need to be freed manually); const std::string& json_str = tif->metadata(); char* json_data_ptr = static_cast<char*>(cucim_malloc(json_str.size() + 1)); memcpy(json_data_ptr, json_str.data(), json_str.size() + 1); std::string_view json_data{ json_data_ptr, json_str.size() }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(level_count); out_metadata.level_ndim(level_ndim); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); return true; } static bool CUCIM_ABI parser_close(CuCIMFileHandle_ptr handle_ptr) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data); delete tif; handle->client_data = nullptr; return true; } static bool CUCIM_ABI reader_read(const CuCIMFileHandle_ptr handle_ptr, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata = nullptr) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data); bool result = tif->read(metadata, request, out_image_data, out_metadata); return result; } static bool CUCIM_ABI writer_write(const CuCIMFileHandle_ptr handle_ptr, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageDataDesc* image_data) { CuCIMFileHandle* handle = reinterpret_cast<CuCIMFileHandle*>(handle_ptr); (void)handle; (void)metadata; (void)image_data; return true; } void fill_interface(cucim::io::format::IImageFormat& iface) { static cucim::io::format::ImageCheckerDesc image_checker = { 0, 0, checker_is_valid }; static cucim::io::format::ImageParserDesc image_parser = { parser_open, parser_parse, parser_close }; static cucim::io::format::ImageReaderDesc image_reader = { reader_read }; static cucim::io::format::ImageWriterDesc image_writer = { writer_write }; // clang-format off static cucim::io::format::ImageFormatDesc image_format_desc = { set_enabled, is_enabled, get_format_name, image_checker, image_parser, image_reader, image_writer }; // clang-format on // clang-format off iface = { &image_format_desc, 1 }; // clang-format on }
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/lzw/lzw_libtiff.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Code below is based on libtiff library which is under BSD-like license, * for providing lzw_decoder implementation. * The code is a port of the following file: * https://gitlab.com/libtiff/libtiff/-/blob/8546f7ee994eacff0a563918096f16e0a6078fa2/libtiff/tif_lzw.c * , which is after v4.3.0. * Please see LICENSE-3rdparty.md for the detail. **/ #ifndef CUSLIDE_LZW_LIBTIFF_H #define CUSLIDE_LZW_LIBTIFF_H #include <cucim/io/device.h> namespace cuslide::lzw { /**************************************************************************** * Define missing types for libtiff's lzw decoder implementation ****************************************************************************/ // Forward declaration struct TIFF; #define COMPRESSION_LZW 5 /* Lempel-Ziv & Welch */ /* Signed size type */ #define TIFF_SSIZE_T signed long typedef TIFF_SSIZE_T tmsize_t; typedef tmsize_t tsize_t; /* i/o size in bytes */ typedef void (*TIFFVoidMethod)(TIFF*); typedef int (*TIFFBoolMethod)(TIFF*); typedef int (*TIFFPreMethod)(TIFF*, uint16_t); typedef int (*TIFFCodeMethod)(TIFF* tif, uint8_t* buf, tmsize_t size, uint16_t sample); typedef int (*TIFFSeekMethod)(TIFF*, uint32_t); typedef void (*TIFFPostMethod)(TIFF* tif, uint8_t* buf, tmsize_t size); typedef uint32_t (*TIFFStripMethod)(TIFF*, uint32_t); typedef void (*TIFFTileMethod)(TIFF*, uint32_t*, uint32_t*); struct TIFF { // Pointer to the buffer to be lzw-compressed/decompressed. uint8_t* tif_rawdata; /* raw data buffer */ // Same with tif_rawcp uint8_t* tif_rawcp = nullptr; /* current spot in raw buffer */ // Size of the buffer to be compressed/decompressed. tmsize_t tif_rawcc = 0; /* bytes unread from raw buffer */ // Codec state initialized by tif->tif_setupdecode which is LZWSetupDecode uint8_t* tif_data = nullptr; /* compression scheme private data */ TIFFBoolMethod tif_setupdecode = nullptr; /* called once before predecode */ TIFFPreMethod tif_predecode = nullptr; /* pre- row/strip/tile decoding */ TIFFCodeMethod tif_decoderow = nullptr; /* scanline decoding routine */ TIFFCodeMethod tif_decodestrip = nullptr; /* strip decoding routine */ TIFFCodeMethod tif_decodetile = nullptr; /* tile decoding routine */ TIFFVoidMethod tif_cleanup = nullptr; /* cleanup state routine */ // Additional method for predictor decoding TIFFPostMethod decodepfunc = nullptr; /* horizontal accumulator */ // Not used in the implementation char* tif_name; /* name of open file */ // Not used in the implementation uint32_t tif_row = 0; /* current scanline */ // Not used in the implementation void* tif_clientdata; /* callback parameter */ }; int TIFFInitLZW(TIFF* tif, int scheme = COMPRESSION_LZW); void horAcc8(uint8_t* cp0, tmsize_t cc, tmsize_t row_size); } // namespace cuslide::lzw #endif // CUSLIDE_LZW_LIBTIFF_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/lzw/lzw_libtiff.cpp
/** * Code below is based on libtiff library which is under BSD-like license, * for providing lzw_decoder implementation. * The code is a port of the following file: * https://gitlab.com/libtiff/libtiff/-/blob/8546f7ee994eacff0a563918096f16e0a6078fa2/libtiff/tif_lzw.c * , which is after v4.3.0. * Please see LICENSE-3rdparty.md for the detail. * * Changes * - Remove v5.0 specification compatibility * - Remove LZW_CHECKEOS which checks for strips w/o EOI code * - Remove encoder logic * - Remove 'register' keyword * - Handle unused variables/methods to avoid compiler errors **/ /**************************************************************************** * Define missing types for libtiff's lzw decoder implementation ****************************************************************************/ #include <cstdint> #include <cstdlib> #include <cstdio> #include <cassert> #include <cstring> #include <cinttypes> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> #include "lzw_libtiff.h" #define _TIFFmalloc(...) cucim_malloc(__VA_ARGS__) #define _TIFFmemset(...) memset(__VA_ARGS__) #define _TIFFfree(...) cucim_free(__VA_ARGS__) #define TIFFErrorExt(tif, module, ...) \ { \ (void)module; \ } \ fprintf(stderr, __VA_ARGS__) namespace cuslide::lzw { // ************************************************************************** /**************************************************************************** * Define methods needed for libtiff's lzw decoder implementation ****************************************************************************/ // The following implementation is based on: // https://github.com/uclouvain/openjpeg/blob/37ac30ceff6640bbab502388c5e0fa0bff23f505/thirdparty/libtiff/tif_predict.c#L268 void horAcc8(uint8_t* cp0, tmsize_t cc, tmsize_t width_nbytes) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_horAcc8)); unsigned char* cp = (unsigned char*)cp0; while (cc > 0) { tmsize_t remaining = width_nbytes; unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; remaining -= 3; cp += 3; while (remaining > 0) { cp[0] = (unsigned char)((cr += cp[0]) & 0xff); cp[1] = (unsigned char)((cg += cp[1]) & 0xff); cp[2] = (unsigned char)((cb += cp[2]) & 0xff); remaining -= 3; cp += 3; } cc -= width_nbytes; } } // ************************************************************************** /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * Rev 5.0 Lempel-Ziv & Welch Compression Support * * This code is derived from the compress program whose code is * derived from software contributed to Berkeley by James A. Woods, * derived from original work by Spencer Thomas and Joseph Orost. * * The original Berkeley copyright notice appears below in its entirety. */ #include <stdio.h> /* * Each strip of data is supposed to be terminated by a CODE_EOI. * If the following #define is included, the decoder will also * check for end-of-strip w/o seeing this code. This makes the * library more robust, but also slower. */ #define LZW_CHECKEOS /* include checks for strips w/o EOI code */ #define MAXCODE(n) ((1L << (n)) - 1) /* * The TIFF spec specifies that encoded bit * strings range from 9 to 12 bits. */ #define BITS_MIN 9 /* start with 9 bits */ #define BITS_MAX 12 /* max of 12 bit strings */ /* predefined codes */ #define CODE_CLEAR 256 /* code to clear string table */ #define CODE_EOI 257 /* end-of-information code */ #define CODE_FIRST 258 /* first free code entry */ #define CODE_MAX MAXCODE(BITS_MAX) #define HSIZE 9001L /* 91% occupancy */ #define HSHIFT (13 - 8) #define CSIZE (MAXCODE(BITS_MAX) + 1L) /* * State block for each open TIFF file using LZW * compression/decompression. Note that the predictor * state block must be first in this data structure. */ typedef struct { unsigned short nbits; /* # of bits/code */ unsigned short maxcode; /* maximum code for lzw_nbits */ unsigned short free_ent; /* next free entry in hash table */ unsigned long nextdata; /* next bits of i/o */ long nextbits; /* # of valid bits in lzw_nextdata */ int rw_mode; /* preserve rw_mode from init */ } LZWBaseState; #define lzw_nbits base.nbits #define lzw_maxcode base.maxcode #define lzw_free_ent base.free_ent #define lzw_nextdata base.nextdata #define lzw_nextbits base.nextbits /* * Encoding-specific state. */ typedef uint16_t hcode_t; /* codes fit in 16 bits */ typedef struct { long hash; hcode_t code; } hash_t; /* * Decoding-specific state. */ typedef struct code_ent { struct code_ent* next; unsigned short length; /* string len, including this token */ unsigned char value; /* data value */ unsigned char firstchar; /* first token of string */ } code_t; typedef int (*decodeFunc)(TIFF*, uint8_t*, tmsize_t, uint16_t); typedef struct { LZWBaseState base; /* Decoding specific data */ long dec_nbitsmask; /* lzw_nbits 1 bits, right adjusted */ long dec_restart; /* restart count */ decodeFunc dec_decode; /* regular or backwards compatible */ code_t* dec_codep; /* current recognized code */ code_t* dec_oldcodep; /* previously recognized code */ code_t* dec_free_entp; /* next free entry */ code_t* dec_maxcodep; /* max available entry */ code_t* dec_codetab; /* kept separate for small machines */ /* Encoding specific data */ int enc_oldcode; /* last code encountered */ long enc_checkpoint; /* point at which to clear table */ long enc_ratio; /* current compression ratio */ long enc_incount; /* (input) data bytes encoded */ long enc_outcount; /* encoded (output) bytes */ uint8_t* enc_rawlimit; /* bound on tif_rawdata buffer */ hash_t* enc_hashtab; /* kept separate for small machines */ } LZWCodecState; #define LZWState(tif) ((LZWBaseState*)(tif)->tif_data) #define DecoderState(tif) ((LZWCodecState*)LZWState(tif)) #define EncoderState(tif) ((LZWCodecState*)LZWState(tif)) static int LZWDecode(TIFF* tif, uint8_t* op0, tmsize_t occ0, uint16_t s); /* * LZW Decoder. */ #define NextCode(tif, sp, bp, code, get) get(sp, bp, code) static int LZWSetupDecode(TIFF* tif) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_LZWSetupDecode)); static const char module[] = "LZWSetupDecode"; LZWCodecState* sp = DecoderState(tif); int code; if (sp == NULL) { /* * Allocate state block so tag methods have storage to record * values. */ tif->tif_data = (uint8_t*)_TIFFmalloc(sizeof(LZWCodecState)); if (tif->tif_data == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } sp = DecoderState(tif); sp->dec_codetab = NULL; sp->dec_decode = NULL; } if (sp->dec_codetab == NULL) { sp->dec_codetab = (code_t*)_TIFFmalloc(CSIZE * sizeof(code_t)); if (sp->dec_codetab == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW code table"); return (0); } /* * Pre-load the table. */ code = 255; do { sp->dec_codetab[code].value = (unsigned char)code; sp->dec_codetab[code].firstchar = (unsigned char)code; sp->dec_codetab[code].length = 1; sp->dec_codetab[code].next = NULL; } while (code--); /* * Zero-out the unused entries */ /* Silence false positive */ /* coverity[overrun-buffer-arg] */ _TIFFmemset(&sp->dec_codetab[CODE_CLEAR], 0, (CODE_FIRST - CODE_CLEAR) * sizeof(code_t)); } return (1); } /* * Setup state for decoding a strip. */ static int LZWPreDecode(TIFF* tif, uint16_t s) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_LZWPreDecode)); static const char module[] = "LZWPreDecode"; LZWCodecState* sp = DecoderState(tif); (void)s; assert(sp != NULL); if (sp->dec_codetab == NULL) { tif->tif_setupdecode(tif); if (sp->dec_codetab == NULL) return (0); } /* * Check for old bit-reversed codes. */ if (tif->tif_rawcc >= 2 && tif->tif_rawdata[0] == 0 && (tif->tif_rawdata[1] & 0x1)) { if (!sp->dec_decode) { TIFFErrorExt(tif->tif_clientdata, module, "Old-style LZW codes not supported"); sp->dec_decode = LZWDecode; } return (0); } else { sp->lzw_maxcode = MAXCODE(BITS_MIN) - 1; sp->dec_decode = LZWDecode; } sp->lzw_nbits = BITS_MIN; sp->lzw_nextbits = 0; sp->lzw_nextdata = 0; sp->dec_restart = 0; sp->dec_nbitsmask = MAXCODE(BITS_MIN); sp->dec_free_entp = sp->dec_codetab + CODE_FIRST; /* * Zero entries that are not yet filled in. We do * this to guard against bogus input data that causes * us to index into undefined entries. If you can * come up with a way to safely bounds-check input codes * while decoding then you can remove this operation. */ _TIFFmemset(sp->dec_free_entp, 0, (CSIZE - CODE_FIRST) * sizeof(code_t)); sp->dec_oldcodep = &sp->dec_codetab[-1]; sp->dec_maxcodep = &sp->dec_codetab[sp->dec_nbitsmask - 1]; return (1); } /* * Decode a "hunk of data". */ #define GetNextCode(sp, bp, code) \ { \ nextdata = (nextdata << 8) | *(bp)++; \ nextbits += 8; \ if (nextbits < nbits) \ { \ nextdata = (nextdata << 8) | *(bp)++; \ nextbits += 8; \ } \ code = (hcode_t)((nextdata >> (nextbits - nbits)) & nbitsmask); \ nextbits -= nbits; \ } static void codeLoop(TIFF* tif, const char* module) { TIFFErrorExt(tif->tif_clientdata, module, "Bogus encoding, loop in the code table; scanline %" PRIu32, tif->tif_row); } static int LZWDecode(TIFF* tif, uint8_t* op0, tmsize_t occ0, uint16_t s) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_LZWDecode)); static const char module[] = "LZWDecode"; LZWCodecState* sp = DecoderState(tif); uint8_t* op = (uint8_t*)op0; long occ = (long)occ0; uint8_t* tp; uint8_t* bp; hcode_t code; int len; long nbits, nextbits, nbitsmask; unsigned long nextdata; code_t *codep, *free_entp, *maxcodep, *oldcodep; (void)s; assert(sp != NULL); assert(sp->dec_codetab != NULL); /* Fail if value does not fit in long. */ if ((tmsize_t)occ != occ0) return (0); /* * Restart interrupted output operation. */ if (sp->dec_restart) { long residue; codep = sp->dec_codep; residue = codep->length - sp->dec_restart; if (residue > occ) { /* * Residue from previous decode is sufficient * to satisfy decode request. Skip to the * start of the decoded string, place decoded * values in the output buffer, and return. */ sp->dec_restart += occ; do { codep = codep->next; } while (--residue > occ && codep); if (codep) { tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); } return (1); } /* * Residue satisfies only part of the decode request. */ op += residue; occ -= residue; tp = op; do { *--tp = codep->value; codep = codep->next; } while (--residue && codep); sp->dec_restart = 0; } bp = (uint8_t*)tif->tif_rawcp; nbits = sp->lzw_nbits; nextdata = sp->lzw_nextdata; nextbits = sp->lzw_nextbits; nbitsmask = sp->dec_nbitsmask; oldcodep = sp->dec_oldcodep; free_entp = sp->dec_free_entp; maxcodep = sp->dec_maxcodep; while (occ > 0) { NextCode(tif, sp, bp, code, GetNextCode); if (code == CODE_EOI) break; if (code == CODE_CLEAR) { do { free_entp = sp->dec_codetab + CODE_FIRST; _TIFFmemset(free_entp, 0, (CSIZE - CODE_FIRST) * sizeof(code_t)); nbits = BITS_MIN; nbitsmask = MAXCODE(BITS_MIN); maxcodep = sp->dec_codetab + nbitsmask - 1; NextCode(tif, sp, bp, code, GetNextCode); } while (code == CODE_CLEAR); /* consecutive CODE_CLEAR codes */ if (code == CODE_EOI) break; if (code > CODE_CLEAR) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "LZWDecode: Corrupted LZW table at scanline %" PRIu32, tif->tif_row); return (0); } *op++ = (uint8_t)code; occ--; oldcodep = sp->dec_codetab + code; continue; } codep = sp->dec_codetab + code; /* * Add the new entry to the code table. */ if (free_entp < &sp->dec_codetab[0] || free_entp >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %" PRIu32, tif->tif_row); return (0); } free_entp->next = oldcodep; if (free_entp->next < &sp->dec_codetab[0] || free_entp->next >= &sp->dec_codetab[CSIZE]) { TIFFErrorExt(tif->tif_clientdata, module, "Corrupted LZW table at scanline %" PRIu32, tif->tif_row); return (0); } free_entp->firstchar = free_entp->next->firstchar; free_entp->length = free_entp->next->length + 1; free_entp->value = (codep < free_entp) ? codep->firstchar : free_entp->firstchar; if (++free_entp > maxcodep) { if (++nbits > BITS_MAX) /* should not happen */ nbits = BITS_MAX; nbitsmask = MAXCODE(nbits); maxcodep = sp->dec_codetab + nbitsmask - 1; } oldcodep = codep; if (code >= 256) { /* * Code maps to a string, copy string * value to output (written in reverse). */ if (codep->length == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Wrong length of decoded string: " "data probably corrupted at scanline %" PRIu32, tif->tif_row); return (0); } if (codep->length > occ) { /* * String is too long for decode buffer, * locate portion that will fit, copy to * the decode buffer, and setup restart * logic for the next decoding call. */ sp->dec_codep = codep; do { codep = codep->next; } while (codep && codep->length > occ); if (codep) { sp->dec_restart = (long)occ; tp = op + occ; do { *--tp = codep->value; codep = codep->next; } while (--occ && codep); if (codep) codeLoop(tif, module); } break; } len = codep->length; tp = op + len; do { *--tp = codep->value; codep = codep->next; } while (codep && tp > op); if (codep) { codeLoop(tif, module); break; } assert(occ >= len); op += len; occ -= len; } else { *op++ = (uint8_t)code; occ--; } } tif->tif_rawcc -= (tmsize_t)((uint8_t*)bp - tif->tif_rawcp); tif->tif_rawcp = (uint8_t*)bp; sp->lzw_nbits = (unsigned short)nbits; sp->lzw_nextdata = nextdata; sp->lzw_nextbits = nextbits; sp->dec_nbitsmask = nbitsmask; sp->dec_oldcodep = oldcodep; sp->dec_free_entp = free_entp; sp->dec_maxcodep = maxcodep; if (occ > 0) { TIFFErrorExt(tif->tif_clientdata, module, "Not enough data at scanline %" PRIu32 " (short %ld bytes)", tif->tif_row, occ); return (0); } return (1); } static void LZWCleanup(TIFF* tif) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_LZWCleanup)); assert(tif->tif_data != 0); if (DecoderState(tif)->dec_codetab) _TIFFfree(DecoderState(tif)->dec_codetab); if (EncoderState(tif)->enc_hashtab) _TIFFfree(EncoderState(tif)->enc_hashtab); _TIFFfree(tif->tif_data); tif->tif_data = NULL; } int TIFFInitLZW(TIFF* tif, int scheme) { PROF_SCOPED_RANGE(PROF_EVENT(lzw_TIFFInitLZW)); static const char module[] = "TIFFInitLZW"; (void)scheme; assert(scheme == COMPRESSION_LZW); /* * Allocate state block so tag methods have storage to record values. */ tif->tif_data = (uint8_t*)_TIFFmalloc(sizeof(LZWCodecState)); if (tif->tif_data == NULL) goto bad; DecoderState(tif)->dec_codetab = NULL; DecoderState(tif)->dec_decode = NULL; EncoderState(tif)->enc_hashtab = NULL; /* * Install codec methods. */ tif->tif_setupdecode = LZWSetupDecode; tif->tif_predecode = LZWPreDecode; tif->tif_decoderow = LZWDecode; tif->tif_decodestrip = LZWDecode; tif->tif_decodetile = LZWDecode; tif->tif_cleanup = LZWCleanup; return (1); bad: TIFFErrorExt(tif->tif_clientdata, module, "No space for LZW state block"); return (0); } /* * Copyright (c) 1985, 1986 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * James A. Woods, derived from original work by Spencer Thomas * and Joseph Orost. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */ } // namespace cuslide::lzw
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/lzw/lzw.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_LZW_H #define CUSLIDE_LZW_H #include <cucim/io/device.h> #include "lzw_libtiff.h" namespace cuslide::lzw { bool decode_lzw(int fd, unsigned char* raw_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device); } #endif // CUSLIDE_LZW_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/lzw/lzw.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * LZW compression: * https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf **/ #include "lzw.h" #include <cstring> #include <stdexcept> #include <unistd.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> namespace cuslide::lzw { bool decode_lzw(int fd, unsigned char* lzw_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device) { (void)out_device; if (dest == nullptr) { throw std::runtime_error("'dest' shouldn't be nullptr in decode_lzw()"); } // Allocate memory only when dest is not null if (*dest == nullptr) { if ((*dest = (unsigned char*)cucim_malloc(dest_nbytes)) == nullptr) { throw std::runtime_error("Unable to allocate uncompressed image buffer"); } } if (lzw_buf == nullptr) { if ((lzw_buf = (unsigned char*)cucim_malloc(size)) == nullptr) { throw std::runtime_error("Unable to allocate buffer for lzw data!"); } if (pread(fd, lzw_buf, size, offset) < 1) { throw std::runtime_error("Unable to read file for lzw data!"); } } else { fd = -1; lzw_buf += offset; } TIFF tif; tif.tif_rawdata = tif.tif_rawcp = lzw_buf; tif.tif_rawcc = size; if (TIFFInitLZW(&tif) == 0) { return false; } if (tif.tif_predecode(&tif, 0 /* unused */) == 0) { goto bad; } if (tif.tif_decodestrip(&tif, *dest, dest_nbytes, 0 /* unused */) == 0) { goto bad; } tif.tif_cleanup(&tif); if (fd != -1) { cucim_free(lzw_buf); } return true; bad: if (fd != -1) { cucim_free(lzw_buf); } tif.tif_cleanup(&tif); return false; } } // namespace cuslide::lzw
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/deflate/deflate.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_DEFLATE_H #define CUSLIDE_DEFLATE_H #include <cucim/io/device.h> namespace cuslide::deflate { bool decode_deflate(int fd, unsigned char* deflate_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device); } #endif // CUSLIDE_DEFLATE_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/deflate/deflate.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Code below is using libdeflate library which is under MIT license * Please see LICENSE-3rdparty.md for the detail. */ #include "deflate.h" #include <stdexcept> #include <unistd.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> #include "libdeflate.h" namespace cuslide::deflate { bool decode_deflate(int fd, unsigned char* deflate_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device) { (void)out_device; struct libdeflate_decompressor* d; if (dest == nullptr) { throw std::runtime_error("'dest' shouldn't be nullptr in decode_deflate()"); } // Allocate memory only when dest is not null if (*dest == nullptr) { if ((*dest = (unsigned char*)cucim_malloc(dest_nbytes)) == nullptr) { throw std::runtime_error("Unable to allocate uncompressed image buffer"); } } { PROF_SCOPED_RANGE(PROF_EVENT(libdeflate_alloc_decompressor)); d = libdeflate_alloc_decompressor(); } if (d == nullptr) { throw std::runtime_error("Unable to allocate decompressor for libdeflate!"); } if (deflate_buf == nullptr) { if ((deflate_buf = (unsigned char*)cucim_malloc(size)) == nullptr) { throw std::runtime_error("Unable to allocate buffer for libdeflate!"); } if (pread(fd, deflate_buf, size, offset) < 1) { throw std::runtime_error("Unable to read file for libdeflate!"); } } else { fd = -1; deflate_buf += offset; } size_t out_size; { PROF_SCOPED_RANGE(PROF_EVENT(libdeflate_zlib_decompress)); libdeflate_zlib_decompress( d, deflate_buf, size /*in_nbytes*/, *dest, dest_nbytes /*out_nbytes_avail*/, &out_size); } if (fd != -1) { cucim_free(deflate_buf); } { PROF_SCOPED_RANGE(PROF_EVENT(libdeflate_free_decompressor)); libdeflate_free_decompressor(d); } return true; } } // namespace cuslide::deflate
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg/libjpeg_turbo.h
/* * Apache License, Version 2.0 * Copyright 2020 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_LIBJPEG_TURBO_H #define CUSLIDE_LIBJPEG_TURBO_H #include <cucim/io/device.h> namespace cuslide::jpeg { bool decode_libjpeg(int fd, unsigned char* jpeg_buf, uint64_t offset, uint64_t size, const void* jpegtable_data, uint32_t jpegtable_count, uint8_t** dest, const cucim::io::Device& out_device, int jpeg_color_space = 0 /* 0: JCS_UNKNOWN, 2: JCS_RGB, 3: JCS_YCbCr */); /** * Reads jpeg header tables. * * TIFF file's TIFFTAG_JPEGTABLES tag has the information about JPEG Quantization table. * This method is for reading the information. * If Quantization table information is not interpreted, the following error message can occurs: * * Quantization table 0x00 was not defined * * @param handle A pointer to tjinstance * @param jpeg_buf jpeg buffer data * @param jpeg_size jpeg buffer size * @return true if it succeeds */ bool read_jpeg_header_tables(const void* handle, const void* jpeg_buf, unsigned long jpeg_size); int jpeg_decode_buffer(const void* handle, const unsigned char* jpegBuf, unsigned long jpegSize, unsigned char* dstBuf, int width, int pitch, int height, int pixelFormat, int flags, int jpegColorSpace = 0 /* 0: JCS_UNKNOWN, 2: JCS_RGB, 3: JCS_YCbCr */); bool get_dimension(const void* image_buf, uint64_t offset, uint64_t size, int* out_width, int* out_height); } // namespace cuslide::jpeg #endif // CUSLIDE_LIBJPEG_TURBO_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg/libjpeg_turbo.cpp
/* * Apache License, Version 2.0 * Copyright 2020 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Code below is derived from the libjpeg-turbo's code which is under three compatible * BSD-style open source licenses * - The IJG (Independent JPEG Group) License * - The Modified (3-clause) BSD License * - The zlib License * Please see LICENSE-3rdparty.md for the detail. * - https://github.com/libjpeg-turbo/libjpeg-turbo/blob/00607ec260efa4cfe10f9b36d6e3d3590ae92d79/tjexample.c * - https://github.com/libjpeg-turbo/libjpeg-turbo/blob/2.0.6/turbojpeg.c#L1241 */ #include "libjpeg_turbo.h" #include <cstring> #include <jpeglib.h> #include <setjmp.h> #include <unistd.h> #include <cucim/profiler/nvtx3.h> #include <turbojpeg.h> static thread_local char errStr[JMSG_LENGTH_MAX] = "No error"; #define DSTATE_START 200 /* after create_decompress */ struct my_error_mgr { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; void (*emit_message)(j_common_ptr, int); boolean warning, stopOnWarning; }; enum { COMPRESS = 1, DECOMPRESS = 2 }; typedef struct _tjinstance { struct jpeg_compress_struct cinfo; struct jpeg_decompress_struct dinfo; struct my_error_mgr jerr; int init, headerRead; char errStr[JMSG_LENGTH_MAX]; boolean isInstanceError; } tjinstance; extern "C" void jpeg_mem_src_tj(j_decompress_ptr, const unsigned char*, unsigned long); namespace cuslide::jpeg { #define THROW_MSG(action, message) \ { \ printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \ retval = -1; \ goto bailout; \ } #define THROWG(m) \ { \ snprintf(errStr, JMSG_LENGTH_MAX, "%s", m); \ retval = -1; \ goto bailout; \ } #define THROW(m) \ { \ snprintf(instance->errStr, JMSG_LENGTH_MAX, "%s", m); \ instance->isInstanceError = TRUE; \ THROWG(m) \ } #define THROW_TJ(action) THROW_MSG(action, tjGetErrorStr2(tjInstance)) #define THROW_UNIX(action) THROW_MSG(action, strerror(errno)) #define DEFAULT_SUBSAMP TJSAMP_444 #define DEFAULT_QUALITY 95 #define NUMSF 16 static const tjscalingfactor sf[NUMSF] = { { 2, 1 }, { 15, 8 }, { 7, 4 }, { 13, 8 }, { 3, 2 }, { 11, 8 }, { 5, 4 }, { 9, 8 }, { 1, 1 }, { 7, 8 }, { 3, 4 }, { 5, 8 }, { 1, 2 }, { 3, 8 }, { 1, 4 }, { 1, 8 } }; static J_COLOR_SPACE pf2cs[TJ_NUMPF] = { JCS_EXT_RGB, JCS_EXT_BGR, JCS_EXT_RGBX, JCS_EXT_BGRX, JCS_EXT_XBGR, JCS_EXT_XRGB, JCS_GRAYSCALE, JCS_EXT_RGBA, JCS_EXT_BGRA, JCS_EXT_ABGR, JCS_EXT_ARGB, JCS_CMYK }; // static const char* subsampName[TJ_NUMSAMP] = { "4:4:4", "4:2:2", "4:2:0", "Grayscale", "4:4:0", "4:1:1" }; // static const char* colorspaceName[TJ_NUMCS] = { "RGB", "YCbCr", "GRAY", "CMYK", "YCCK" }; bool decode_libjpeg(int fd, unsigned char* jpeg_buf, uint64_t offset, uint64_t size, const void* jpegtable_data, uint32_t jpegtable_count, uint8_t** dest, const cucim::io::Device& out_device, int jpeg_color_space) { (void)out_device; // tjscalingfactor scalingFactor = { 1, 1 }; tjtransform xform; int flags = 0; // flags |= TJFLAG_FASTUPSAMPLE; // flags |= TJFLAG_FASTDCT; // flags |= TJFLAG_ACCURATEDCT; int width, height; int retval = 0, pixelFormat = TJPF_RGB; (void)retval; // retval is used by macro THROW tjhandle tjInstance = nullptr; memset(&xform, 0, sizeof(tjtransform)); /* Input image is a JPEG image. Decompress and/or transform it. */ int inSubsamp, inColorspace; // int doTransform = (xform.op != TJXOP_NONE || xform.options != 0 || xform.customFilter != NULL); /* Read the JPEG file/buffer into memory. */ if (size == 0) THROW_MSG("determining input file size", "Input file contains no data"); if (dest == nullptr) { THROW_MSG("checking dest ptr", "'dest' shouldn't be nullptr in decode_libjpeg()"); } if (jpeg_buf == nullptr) { { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjAlloc)); if ((jpeg_buf = (unsigned char*)tjAlloc(size)) == nullptr) THROW_UNIX("allocating JPEG buffer"); } if (pread(fd, jpeg_buf, size, offset) < 1) THROW_UNIX("reading input file"); } else { fd = -1; jpeg_buf += offset; } { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjInitDecompress)); if ((tjInstance = tjInitDecompress()) == nullptr) THROW_TJ("initializing decompressor"); } // Read jpeg tables if exists if (jpegtable_count) { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_read_jpeg_header_tables)); if (!read_jpeg_header_tables(tjInstance, jpegtable_data, jpegtable_count)) { THROW_TJ("reading JPEG header tables"); } } { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjDecompressHeader3)); if (tjDecompressHeader3(tjInstance, jpeg_buf, size, &width, &height, &inSubsamp, &inColorspace) < 0) THROW_TJ("reading JPEG header"); } // printf("%s Image: %d x %d pixels, %s subsampling, %s colorspace\n", (doTransform ? "Transformed" : "Input"), // width, // height, subsampName[inSubsamp], colorspaceName[inColorspace]); // Allocate memory only when dest is not null if (*dest == nullptr) { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjAlloc)); if ((*dest = (unsigned char*)tjAlloc(width * height * tjPixelSize[pixelFormat])) == nullptr) THROW_UNIX("Unable to allocate uncompressed image buffer"); } { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_jpeg_decode_buffer)); if (jpeg_decode_buffer(tjInstance, jpeg_buf, size, (unsigned char*)*dest, width, 0, height, pixelFormat, flags, jpeg_color_space) < 0) THROW_TJ("decompressing JPEG image"); } if (fd != -1) { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjFree)); tjFree(jpeg_buf); } { PROF_SCOPED_RANGE(PROF_EVENT(decoder_libjpeg_turbo_tjDestroy)); tjDestroy(tjInstance); } return true; bailout: if (tjInstance) tjDestroy(tjInstance); if (fd != -1) { tjFree(jpeg_buf); } return false; } bool read_jpeg_header_tables(const void* handle, const void* jpeg_buf, unsigned long jpeg_size) { tjinstance* instance = (tjinstance*)handle; j_decompress_ptr dinfo = NULL; dinfo = &instance->dinfo; instance->jerr.warning = FALSE; instance->isInstanceError = FALSE; if (setjmp(instance->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ return false; } jpeg_mem_src_tj(dinfo, static_cast<const unsigned char*>(jpeg_buf), jpeg_size); if (jpeg_read_header(dinfo, FALSE) != JPEG_HEADER_TABLES_ONLY) { return false; } return true; } // The following implementation is borrowed from tjDecompress2() in libjpeg-turbo // (https://github.com/libjpeg-turbo/libjpeg-turbo/blob/2.0.6/turbojpeg.c#L1241) // to set color space of the input image from TIFF metadata. int jpeg_decode_buffer(const void* handle, const unsigned char* jpegBuf, unsigned long jpegSize, unsigned char* dstBuf, int width, int pitch, int height, int pixelFormat, int flags, int jpegColorSpace) { JSAMPROW* row_pointer = NULL; int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh; // Replace `GET_DINSTANCE(handle);` by cuCIM tjinstance* instance = (tjinstance*)handle; j_decompress_ptr dinfo = NULL; dinfo = &instance->dinfo; instance->jerr.warning = FALSE; instance->isInstanceError = FALSE; instance->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE; if ((instance->init & DECOMPRESS) == 0) THROW("tjDecompress2(): Instance has not been initialized for decompression"); if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || width < 0 || pitch < 0 || height < 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF) THROW("tjDecompress2(): Invalid argument"); #ifndef NO_PUTENV if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1"); else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1"); else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1"); #endif if (setjmp(instance->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize); jpeg_read_header(dinfo, TRUE); // Modified to set jpeg_color_space by cuCIM if (jpegColorSpace) { dinfo->jpeg_color_space = static_cast<J_COLOR_SPACE>(jpegColorSpace); } instance->dinfo.out_color_space = pf2cs[pixelFormat]; if (flags & TJFLAG_FASTDCT) instance->dinfo.dct_method = JDCT_FASTEST; if (flags & TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling = FALSE; jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height; if (width == 0) width = jpegwidth; if (height == 0) height = jpegheight; for (i = 0; i < NUMSF; i++) { scaledw = TJSCALED(jpegwidth, sf[i]); scaledh = TJSCALED(jpegheight, sf[i]); if (scaledw <= width && scaledh <= height) break; } if (i >= NUMSF) THROW("tjDecompress2(): Could not scale down to desired image dimensions"); width = scaledw; height = scaledh; dinfo->scale_num = sf[i].num; dinfo->scale_denom = sf[i].denom; jpeg_start_decompress(dinfo); if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat]; if ((row_pointer = (JSAMPROW*)malloc(sizeof(JSAMPROW) * dinfo->output_height)) == NULL) THROW("tjDecompress2(): Memory allocation failure"); if (setjmp(instance->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } for (i = 0; i < (int)dinfo->output_height; i++) { if (flags & TJFLAG_BOTTOMUP) row_pointer[i] = &dstBuf[(dinfo->output_height - i - 1) * (size_t)pitch]; else row_pointer[i] = &dstBuf[i * (size_t)pitch]; } while (dinfo->output_scanline < dinfo->output_height) jpeg_read_scanlines(dinfo, &row_pointer[dinfo->output_scanline], dinfo->output_height - dinfo->output_scanline); jpeg_finish_decompress(dinfo); bailout: if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo); free(row_pointer); if (instance->jerr.warning) retval = -1; instance->jerr.stopOnWarning = FALSE; return retval; } bool get_dimension(const void* image_buf, uint64_t offset, uint64_t size, int* out_width, int* out_height) { int retval = 0; (void)retval; // retval is used by macro THROW tjhandle tjInstance = nullptr; int inSubsamp, inColorspace; if (image_buf == nullptr || size == 0) THROW_MSG("determining input buffer size", "Input buffer contains no data"); if ((tjInstance = tjInitDecompress()) == nullptr) THROW_TJ("initializing decompressor"); if (tjDecompressHeader3(tjInstance, static_cast<const unsigned char*>(image_buf) + offset, size, out_width, out_height, &inSubsamp, &inColorspace) < 0) THROW_TJ("reading JPEG header"); tjDestroy(tjInstance); return true; bailout: if (tjInstance) tjDestroy(tjInstance); return false; } } // namespace cuslide::jpeg
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg/libnvjpeg.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "libnvjpeg.h" #include <cstring> #include <unistd.h> namespace cuslide::jpeg { #define THROW(action, message) \ { \ printf("ERROR in line %d while %s:\n%s\n", __LINE__, action, message); \ retval = -1; \ goto bailout; \ } bool decode_libnvjpeg(const int fd, const unsigned char* jpeg_buf, const uint64_t offset, const uint64_t size, const void* jpegtable_data, const uint32_t jpegtable_count, uint8_t** dest, const cucim::io::Device& out_device) { (void)out_device; (void)fd; (void)jpeg_buf; (void)offset; (void)size; (void)jpegtable_data; (void)jpegtable_count; (void)dest; (void)out_device; return true; } } // namespace cuslide::jpeg
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg/libnvjpeg.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_LIBNVJPEG_H #define CUSLIDE_LIBNVJPEG_H #include <cucim/io/device.h> namespace cuslide::jpeg { EXPORT_VISIBLE bool decode_libnvjpeg(int fd, const unsigned char* jpeg_buf, uint64_t offset, uint64_t size, const void* jpegtable_data, uint32_t jpegtable_count, uint8_t** dest, const cucim::io::Device& out_device); } // namespace cuslide::jpeg #endif // CUSLIDE_LIBNVJPEG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/raw/raw.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Code below is using libdeflate library which is under MIT license * Please see LICENSE-3rdparty.md for the detail. */ #include "raw.h" #include <cstring> #include <stdexcept> #include <unistd.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> namespace cuslide::raw { bool decode_raw(int fd, unsigned char* raw_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device) { (void)out_device; if (dest == nullptr) { throw std::runtime_error("'dest' shouldn't be nullptr in decode_raw()"); } // Allocate memory only when dest is not null if (*dest == nullptr) { if ((*dest = (unsigned char*)cucim_malloc(dest_nbytes)) == nullptr) { throw std::runtime_error("Unable to allocate uncompressed image buffer"); } } if (raw_buf == nullptr) { if ((raw_buf = (unsigned char*)cucim_malloc(size)) == nullptr) { throw std::runtime_error("Unable to allocate buffer for raw data!"); } if (pread(fd, raw_buf, size, offset) < 1) { throw std::runtime_error("Unable to read file for raw data!"); } } else { fd = -1; raw_buf += offset; } memcpy(*dest, raw_buf, dest_nbytes); if (fd != -1) { cucim_free(raw_buf); } return true; } } // namespace cuslide::raw
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/raw/raw.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_RAW_H #define CUSLIDE_RAW_H #include <cucim/io/device.h> namespace cuslide::raw { bool decode_raw(int fd, unsigned char* raw_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device); } #endif // CUSLIDE_RAW_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/color_conversion.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Code below is derived from the openjpeg's code which is under BSD-2-Clause License. * Please see LICENSE-3rdparty.md for the detail. * - https://github.com/uclouvain/openjpeg/blob/v2.4.0/src/bin/common/color.c#L403 */ #include "color_conversion.h" #include <cucim/profiler/nvtx3.h> #include "color_table.h" namespace cuslide::jpeg2k { static inline uint8_t clamp(int32_t x) { return (x < 0) ? 0 : ((x > 255) ? 255 : x); } void fast_sycc422_to_rgb(opj_image_t* image, uint8_t* dest) { PROF_SCOPED_RANGE(PROF_EVENT(jpeg2k_fast_sycc422_to_rgb)); const opj_image_comp_t* comps = image->comps; const size_t maxw = (size_t)comps[0].w; const size_t maxh = (size_t)comps[0].h; const int* y = image->comps[0].data; const int* cb = image->comps[1].data; const int* cr = image->comps[2].data; /* if image->x0 is odd, then first column shall use Cb/Cr = 0 */ size_t offx = image->x0 & 1U; size_t loopmaxw = maxw - offx; size_t j_max = (loopmaxw & ~(size_t)1U); uint8_t c0, c1, c2; int16_t R, G, B; size_t i, j; for (i = 0U; i < maxh; ++i) { if (offx > 0U) { c0 = *y; c1 = 0; c2 = 0; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; } for (j = 0U; j < j_max; j += 2U) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *y; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; ++cb; ++cr; } if (j < loopmaxw) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; ++cb; ++cr; } } } void fast_sycc420_to_rgb(opj_image_t* image, uint8_t* dest) { PROF_SCOPED_RANGE(PROF_EVENT(jpeg2k_fast_sycc420_to_rgb)); const opj_image_comp_t* comps = image->comps; const size_t maxw = (size_t)comps[0].w; const size_t maxh = (size_t)comps[0].h; const int* y = image->comps[0].data; const int* cb = image->comps[1].data; const int* cr = image->comps[2].data; /* if image->x0 is odd, then first column shall use Cb/Cr = 0 */ size_t offx = image->x0 & 1U; size_t loopmaxw = maxw - offx; size_t j_max = (loopmaxw & ~(size_t)1U); /* if image->y0 is odd, then first line shall use Cb/Cr = 0 */ size_t offy = image->y0 & 1U; size_t loopmaxh = maxh - offy; size_t i_max = (loopmaxh & ~(size_t)1U); size_t width_nbytes = maxw * 3; uint8_t c0, c1, c2; int16_t R, G, B; uint8_t* ndest; const int* ny; size_t i, j; if (offy > 0U) { for (j = 0; j < maxw; ++j) { c0 = *y; c1 = 0; c2 = 0; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; } } for (i = 0U; i < i_max; i += 2U) { ny = y + maxw; ndest = dest + width_nbytes; if (offx > 0U) { c0 = *y; c1 = 0; c2 = 0; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *ny; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *ndest++ = R; *ndest++ = G; *ndest++ = B; ++ny; } for (j = 0; j < j_max; j += 2U) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *y; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *ny; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *ndest++ = R; *ndest++ = G; *ndest++ = B; ++ny; c0 = *ny; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *ndest++ = R; *ndest++ = G; *ndest++ = B; ++ny; ++cb; ++cr; } if (j < loopmaxw) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *ny; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *ndest++ = R; *ndest++ = G; *ndest++ = B; ++ny; ++cb; ++cr; } y += maxw; dest += width_nbytes; } if (i < loopmaxh) { for (j = 0U; j < j_max; j += 2U) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; c0 = *y; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; ++cb; ++cr; } if (j < maxw) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; } } } void fast_sycc444_to_rgb(opj_image_t* image, uint8_t* dest) { PROF_SCOPED_RANGE(PROF_EVENT(jpeg2k_fast_sycc444_to_rgb)); const opj_image_comp_t* comps = image->comps; const size_t maxw = (size_t)comps[0].w; const size_t maxh = (size_t)comps[0].h; const size_t max = maxw * maxh; const int* y = image->comps[0].data; const int* cb = image->comps[1].data; const int* cr = image->comps[2].data; uint8_t c0, c1, c2; int16_t R, G, B; size_t i; for (i = 0U; i < max; ++i) { c0 = *y; c1 = *cb; c2 = *cr; R = clamp(c0 + R_Cr[c2]); G = clamp(c0 + ((G_Cb[c1] + G_Cr[c2]) >> 16)); B = clamp(c0 + B_Cb[c1]); *dest++ = R; *dest++ = G; *dest++ = B; ++y; ++cb; ++cr; } } void fast_image_to_rgb(opj_image_t* image, uint8_t* dest) { PROF_SCOPED_RANGE(PROF_EVENT(jpeg2k_fast_image_to_rgb)); opj_image_comp_t* comps = image->comps; uint32_t width = comps[0].w; uint32_t height = comps[0].h; uint32_t items = width * height; uint8_t* buf = dest; int32_t* comp0 = comps[0].data; int32_t* comp1 = comps[1].data; int32_t* comp2 = comps[2].data; for (uint32_t i = 0; i < items; ++i) { *(buf++) = comp0[i]; *(buf++) = comp1[i]; *(buf++) = comp2[i]; } } } // namespace cuslide::jpeg2k
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/color_conversion.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_JPEG2K_COLOR_CONVERSION_H #define CUSLIDE_JPEG2K_COLOR_CONVERSION_H #include <cstdint> #include <openjpeg.h> namespace cuslide::jpeg2k { void fast_sycc420_to_rgb(opj_image_t* image, uint8_t* dest); void fast_sycc422_to_rgb(opj_image_t* image, uint8_t* dest); void fast_sycc444_to_rgb(opj_image_t* image, uint8_t* dest); void fast_image_to_rgb(opj_image_t* image, uint8_t* dest); } // namespace cuslide::jpeg2k #endif // CUSLIDE_JPEG2K_COLOR_CONVERSION_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/gen_color_table.py
# # Copyright (c) 2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # https://github.com/uclouvain/openjpeg/blob/v2.4.0/src/bin/common/color.c#L60 ############################################################################### # Matrix for sYCC, Amendment 1 to IEC 61966-2-1 # # Y : 0.299 0.587 0.114 :R # Cb: -0.1687 -0.3312 0.5 :G # Cr: 0.5 -0.4187 -0.0812 :B # # Inverse: # # R: 1 -3.68213e-05 1.40199 :Y # G: 1.00003 -0.344125 -0.714128 :Cb - 2^(prec - 1) # B: 0.999823 1.77204 -8.04142e-06 :Cr - 2^(prec - 1) ############################################################################### """ Color Conversion table generator. Instrumented on the following image to see which pre-calculation can minimize errors, compared with openjpeg's slow-color-conversion logic. We chose to use the approach of `count_cr0.5.txt` >>> input_file = "notebooks/input/TUPAC-TR-467.svs" >>> img = CuImage(input_file) >>> region = img.read_region(level=2) Configuration for `gen_g_cb()` and `gen_g_cr()` was changed. ```c++ if (*buf != comp0[i]) { fprintf(stdout, "%u(0): %d != %d #%d\n ", i, *buf, comp0[i], ((uint8_t)(*buf) - (uint8_t)comp0[i])); } *(buf++) = comp0[i]; if (*buf != comp1[i]) { fprintf(stdout, "%u(1): %d != %d #%d\n", i, *buf, comp1[i], ((uint8_t)(*buf) - (uint8_t)comp1[i])); } *(buf++) = comp1[i]; if (*buf != comp2[i]) { fprintf(stdout, "%u(2): %d != %d #%d\n", i, *buf, comp2[i], ((uint8_t)(*buf) - (uint8_t)comp2[i])); } *(buf++) = comp2[i]; ``` ❯ grep -c "#-1" count_both0.5.txt 1286 ❯ grep -c "#1" count_both0.5.txt 1275184 ❯ grep -c "#1" count_both0.txt 0 ❯ grep -c "#-1" count_both0.txt 1125962 ❯ grep -c "#-1" count_cb0.5.txt 511399 ❯ grep -c "#1" count_cb0.5.txt 248788 ❯ grep -c "#-1" count_round_cb0.5.txt 511399 ❯ grep -c "#1" count_round_cb0.5.txt 248788 ❯ grep -c "#-1" count_cr0.5.txt 511399 ❯ grep -c "#1" count_cr0.5.txt 248788 ❯ grep -c "#-1" count_round_cr0.5.txt 511399 ❯ grep -c "#1" count_round_cr0.5.txt 248788 ❯ grep -c "#-1" count_round_short_cb0.5.txt 508465 ❯ grep -c "#1" count_round_short_cb0.5.txt 248808 """ def gen_r_cr(): """ Generate the R-Cr table. """ r_cr = [0] * 256 for i in range(256): r_cr[i] = int(1.40199 * (i - 128)) return r_cr def gen_g_cb(): """ Generate the G-Cb table. """ g_cb = [0] * 256 for i in range(256): g_cb[i] = int((-0.344125 * (i - 128)) * (1 << 16)) return g_cb def gen_g_cr(): """ Generate the G-Cr table. """ g_cr = [0] * 256 for i in range(256): g_cr[i] = int((-0.714128 * (i - 128) + 0.5) * (1 << 16)) return g_cr def gen_b_cb(): """ Generate the B-Cb table. """ b_cb = [0] * 256 for i in range(256): b_cb[i] = int((1.77204 * (i - 128))) return b_cb TEMPLATE = """// This file is generated by gen_color_table.py // clang-format off #ifndef CUSLIDE_JPEG2K_COLOR_TABLE_H #define CUSLIDE_JPEG2K_COLOR_TABLE_H namespace cuslide::jpeg2k { static constexpr int16_t R_Cr[256] = { %(r_cr)s }; static constexpr int32_t G_Cb[256] = { %(g_cb)s }; static constexpr int32_t G_Cr[256] = { %(g_cr)s }; static constexpr int16_t B_Cb[256] = { %(b_cb)s }; } // namespace cuslide::jpeg2k #endif // CUSLIDE_JPEG2K_COLOR_TABLE_H // clang-format on """ def gen_list(values: list, width: int, align: int = 8): text = [] for i in range(0, len(values), width): text.append( ", ".join( ("{:>" + str(align) + "}").format(item) for item in values[i : i + width] ) ) return ",\n ".join(text) def main(output_file_name: str) -> int: r_cr = gen_list(list(gen_r_cr()), 10, 4) g_cb = gen_list(list(gen_g_cb()), 10) g_cr = gen_list(list(gen_g_cr()), 10) b_cb = gen_list(list(gen_b_cb()), 10, 4) with open(output_file_name, "w") as f: f.write( TEMPLATE % {"r_cr": r_cr, "g_cb": g_cb, "g_cr": g_cr, "b_cb": b_cb} ) return 0 if __name__ == "__main__": import sys if len(sys.argv) != 2: print("Usage: gen_color_table.py <output_file_name>") sys.exit(1) sys.exit(main(sys.argv[1]))
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/libopenjpeg.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "libopenjpeg.h" #include <string.h> #include <stdlib.h> #include <unistd.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> #include <fmt/format.h> #include <openjpeg.h> #include "color_conversion.h" #define ALIGN_UP(x, align_to) (((uint64_t)(x) + ((uint64_t)(align_to)-1)) & ~((uint64_t)(align_to)-1)) #define ALIGN_SIZE 16 // Extern methods from 'deps-libopenjpeg-src/src/bin/common/color.h' extern "C" { void color_sycc_to_rgb(opj_image_t* img); void color_apply_icc_profile(opj_image_t* image); } namespace cuslide::jpeg2k { /** * Code below is derived from the openjpeg's code which is under BSD-2-Clause License * Please see LICENSE-3rdparty.md for the detail. * - https://github.com/uclouvain/openjpeg/blob/v2.4.0/tests/test_decode_area.c * - https://github.com/uclouvain/openjpeg/blob/v2.4.0/src/lib/openjpip/jp2k_decoder.c#L46 */ struct UserData { uint8_t* buf = nullptr; uint64_t size = 0; uint64_t offset = 0; }; static void error_callback(const char* msg, void* client_data) { (void)client_data; fprintf(stderr, "[Error] %s\n", msg); } static void warning_callback(const char* msg, void* client_data) { (void)client_data; fprintf(stderr, "[Warning] %s\n", msg); } static OPJ_SIZE_T read_callback(void* p_buffer, OPJ_SIZE_T p_nb_bytes, void* p_user_data) { auto data = static_cast<UserData*>(p_user_data); if (data->offset >= data->size) { return -1; } if (data->offset + p_nb_bytes >= data->size) { size_t nb_bytes_to_read = data->size - data->offset; memcpy(p_buffer, data->buf + data->offset, nb_bytes_to_read); data->offset = data->size; return nb_bytes_to_read; } if (p_nb_bytes == 0) { return -1; } memcpy(p_buffer, data->buf + data->offset, p_nb_bytes); data->offset += p_nb_bytes; return p_nb_bytes; } static OPJ_OFF_T skip_callback(OPJ_OFF_T p_nb_bytes, void* p_user_data) { auto data = static_cast<UserData*>(p_user_data); if (data->offset + p_nb_bytes >= data->size) { uint64_t skip_count = data->size - data->offset; data->offset = data->size; return skip_count; } data->offset += p_nb_bytes; return p_nb_bytes; } static OPJ_BOOL seek_callback(OPJ_OFF_T p_nb_bytes, void* p_user_data) { auto data = static_cast<UserData*>(p_user_data); if (p_nb_bytes < 0) { data->offset = 0; return OPJ_FALSE; } if (static_cast<uint64_t>(p_nb_bytes) >= data->size) { data->offset = data->size; return OPJ_FALSE; } data->offset = p_nb_bytes; return OPJ_TRUE; } bool decode_libopenjpeg(int fd, unsigned char* jpeg_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device, ColorSpace color_space) { (void)out_device; if (dest == nullptr) { throw std::runtime_error("'dest' shouldn't be nullptr in decode_libopenjpeg()"); } // Allocate memory only when dest is not null if (*dest == nullptr) { if ((*dest = (unsigned char*)cucim_malloc(dest_nbytes)) == nullptr) { throw std::runtime_error("Unable to allocate uncompressed image buffer"); } } if (jpeg_buf == nullptr) { if ((jpeg_buf = (unsigned char*)cucim_malloc(size)) == nullptr) { throw std::runtime_error("Unable to allocate buffer for libopenjpeg!"); } if (pread(fd, jpeg_buf, size, offset) < 1) { throw std::runtime_error("Unable to read file for libopenjpeg!"); } } else { fd = -1; jpeg_buf += offset; } opj_stream_t* stream; { PROF_SCOPED_RANGE(PROF_EVENT(opj_stream_create)); stream = opj_stream_create(size, OPJ_TRUE); } if (!stream) { throw std::runtime_error("[Error] Failed to create stream\n"); } UserData data{ jpeg_buf, size, 0 }; opj_stream_set_user_data(stream, &data, nullptr); opj_stream_set_user_data_length(stream, size); opj_stream_set_read_function(stream, read_callback); opj_stream_set_skip_function(stream, skip_callback); opj_stream_set_seek_function(stream, seek_callback); opj_codec_t* codec; { PROF_SCOPED_RANGE(PROF_EVENT(opj_create_decompress)); codec = opj_create_decompress(OPJ_CODEC_J2K); } if (!codec) { throw std::runtime_error("[Error] Failed to create codec\n"); } // Register the event callbacks opj_set_warning_handler(codec, warning_callback, nullptr); opj_set_error_handler(codec, error_callback, nullptr); opj_dparameters_t parameters; opj_set_default_decoder_parameters(&parameters); opj_setup_decoder(codec, &parameters); opj_image_t* image = nullptr; try { { PROF_SCOPED_RANGE(PROF_EVENT(opj_read_header)); if (!opj_read_header(stream, codec, &image)) { throw std::runtime_error("[Error] Failed to read header from OpenJpeg stream\n"); } } if (image->numcomps != 3) { throw std::runtime_error("[Error] Only RGB images are supported\n"); } { PROF_SCOPED_RANGE(PROF_EVENT(opj_decode)); if (!opj_decode(codec, stream, image)) { throw std::runtime_error("[Error] Failed to decode image\n"); } } if (image->color_space != OPJ_CLRSPC_SYCC) { if (color_space == ColorSpace::kSYCC) { image->color_space = OPJ_CLRSPC_SYCC; } else if (color_space == ColorSpace::kRGB) { image->color_space = OPJ_CLRSPC_SRGB; } } // YCbCr 4:2:2 or 4:2:0 or 4:4:4 if ((image->color_space == OPJ_CLRSPC_SYCC) && (image->icc_profile_buf == nullptr)) { uint32_t& comp0_dx = image->comps[0].dx; uint32_t& comp0_dy = image->comps[0].dy; uint32_t& comp1_dx = image->comps[1].dx; uint32_t& comp1_dy = image->comps[1].dy; uint32_t& comp2_dx = image->comps[2].dx; uint32_t& comp2_dy = image->comps[2].dy; if ((comp0_dx == 1) && (comp1_dx == 2) && (comp2_dx == 2) && (comp0_dy == 1) && (comp1_dy == 1) && (comp2_dy == 1)) { fast_sycc422_to_rgb(image, *dest); // horizontal sub-sample only } else if ((comp0_dx == 1) && (comp1_dx == 2) && (comp2_dx == 2) && (comp0_dy == 1) && (comp1_dy == 2) && (comp2_dy == 2)) { fast_sycc420_to_rgb(image, *dest); // horizontal and vertical sub-sample } else if ((comp0_dx == 1) && (comp1_dx == 1) && (comp2_dx == 1) && (comp0_dy == 1) && (comp1_dy == 1) && (comp2_dy == 1)) { fast_sycc444_to_rgb(image, *dest); // no sub-sample } else { throw std::runtime_error(fmt::format( "[Error] decode_libopenjpeg cannot convert the image (comp0_dx:{}, comp0_dy:{}, comp1_dx:{}, comp1_dy:{}, comp2_dx:{}, comp2_dy:{})\n", comp0_dx, comp0_dy, comp1_dx, comp1_dy, comp2_dx, comp2_dy)); } } else { if (image->color_space == OPJ_CLRSPC_SYCC) { PROF_SCOPED_RANGE(PROF_EVENT(color_sycc_to_rgb)); color_sycc_to_rgb(image); } if (image->icc_profile_buf) { { PROF_SCOPED_RANGE(PROF_EVENT(color_apply_icc_profile)); color_apply_icc_profile(image); } image->icc_profile_len = 0; free(image->icc_profile_buf); image->icc_profile_buf = nullptr; } if (image->comps) { fast_image_to_rgb(image, *dest); } } } catch (const std::runtime_error& e) { { PROF_SCOPED_RANGE(PROF_EVENT(opj_destructions)); opj_destroy_codec(codec); opj_stream_destroy(stream); opj_image_destroy(image); } if (fd != -1) { cucim_free(jpeg_buf); } throw e; } { PROF_SCOPED_RANGE(PROF_EVENT(opj_destructions)); opj_destroy_codec(codec); opj_stream_destroy(stream); opj_image_destroy(image); } if (fd != -1) { cucim_free(jpeg_buf); } return true; } } // namespace cuslide::jpeg2k
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/color_table.h
// This file is generated by gen_color_table.py // clang-format off #ifndef CUSLIDE_JPEG2K_COLOR_TABLE_H #define CUSLIDE_JPEG2K_COLOR_TABLE_H namespace cuslide::jpeg2k { static constexpr int16_t R_Cr[256] = { -179, -178, -176, -175, -173, -172, -171, -169, -168, -166, -165, -164, -162, -161, -159, -158, -157, -155, -154, -152, -151, -150, -148, -147, -145, -144, -143, -141, -140, -138, -137, -135, -134, -133, -131, -130, -128, -127, -126, -124, -123, -121, -120, -119, -117, -116, -114, -113, -112, -110, -109, -107, -106, -105, -103, -102, -100, -99, -98, -96, -95, -93, -92, -91, -89, -88, -86, -85, -84, -82, -81, -79, -78, -77, -75, -74, -72, -71, -70, -68, -67, -65, -64, -63, -61, -60, -58, -57, -56, -54, -53, -51, -50, -49, -47, -46, -44, -43, -42, -40, -39, -37, -36, -35, -33, -32, -30, -29, -28, -26, -25, -23, -22, -21, -19, -18, -16, -15, -14, -12, -11, -9, -8, -7, -5, -4, -2, -1, 0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 14, 15, 16, 18, 19, 21, 22, 23, 25, 26, 28, 29, 30, 32, 33, 35, 36, 37, 39, 40, 42, 43, 44, 46, 47, 49, 50, 51, 53, 54, 56, 57, 58, 60, 61, 63, 64, 65, 67, 68, 70, 71, 72, 74, 75, 77, 78, 79, 81, 82, 84, 85, 86, 88, 89, 91, 92, 93, 95, 96, 98, 99, 100, 102, 103, 105, 106, 107, 109, 110, 112, 113, 114, 116, 117, 119, 120, 121, 123, 124, 126, 127, 128, 130, 131, 133, 134, 135, 137, 138, 140, 141, 143, 144, 145, 147, 148, 150, 151, 152, 154, 155, 157, 158, 159, 161, 162, 164, 165, 166, 168, 169, 171, 172, 173, 175, 176, 178 }; static constexpr int32_t G_Cb[256] = { 2886729, 2864177, 2841624, 2819072, 2796519, 2773966, 2751414, 2728861, 2706309, 2683756, 2661203, 2638651, 2616098, 2593546, 2570993, 2548441, 2525888, 2503335, 2480783, 2458230, 2435678, 2413125, 2390573, 2368020, 2345467, 2322915, 2300362, 2277810, 2255257, 2232705, 2210152, 2187599, 2165047, 2142494, 2119942, 2097389, 2074836, 2052284, 2029731, 2007179, 1984626, 1962074, 1939521, 1916968, 1894416, 1871863, 1849311, 1826758, 1804206, 1781653, 1759100, 1736548, 1713995, 1691443, 1668890, 1646338, 1623785, 1601232, 1578680, 1556127, 1533575, 1511022, 1488470, 1465917, 1443364, 1420812, 1398259, 1375707, 1353154, 1330601, 1308049, 1285496, 1262944, 1240391, 1217839, 1195286, 1172733, 1150181, 1127628, 1105076, 1082523, 1059971, 1037418, 1014865, 992313, 969760, 947208, 924655, 902103, 879550, 856997, 834445, 811892, 789340, 766787, 744235, 721682, 699129, 676577, 654024, 631472, 608919, 586366, 563814, 541261, 518709, 496156, 473604, 451051, 428498, 405946, 383393, 360841, 338288, 315736, 293183, 270630, 248078, 225525, 202973, 180420, 157868, 135315, 112762, 90210, 67657, 45105, 22552, 0, -22552, -45105, -67657, -90210, -112762, -135315, -157868, -180420, -202973, -225525, -248078, -270630, -293183, -315736, -338288, -360841, -383393, -405946, -428498, -451051, -473604, -496156, -518709, -541261, -563814, -586366, -608919, -631472, -654024, -676577, -699129, -721682, -744235, -766787, -789340, -811892, -834445, -856997, -879550, -902103, -924655, -947208, -969760, -992313, -1014865, -1037418, -1059971, -1082523, -1105076, -1127628, -1150181, -1172733, -1195286, -1217839, -1240391, -1262944, -1285496, -1308049, -1330601, -1353154, -1375707, -1398259, -1420812, -1443364, -1465917, -1488470, -1511022, -1533575, -1556127, -1578680, -1601232, -1623785, -1646338, -1668890, -1691443, -1713995, -1736548, -1759100, -1781653, -1804206, -1826758, -1849311, -1871863, -1894416, -1916968, -1939521, -1962074, -1984626, -2007179, -2029731, -2052284, -2074836, -2097389, -2119942, -2142494, -2165047, -2187599, -2210152, -2232705, -2255257, -2277810, -2300362, -2322915, -2345467, -2368020, -2390573, -2413125, -2435678, -2458230, -2480783, -2503335, -2525888, -2548441, -2570993, -2593546, -2616098, -2638651, -2661203, -2683756, -2706309, -2728861, -2751414, -2773966, -2796519, -2819072, -2841624, -2864177 }; static constexpr int32_t G_Cr[256] = { 6023307, 5976506, 5929705, 5882904, 5836103, 5789302, 5742501, 5695700, 5648899, 5602098, 5555296, 5508495, 5461694, 5414893, 5368092, 5321291, 5274490, 5227689, 5180888, 5134087, 5087286, 5040484, 4993683, 4946882, 4900081, 4853280, 4806479, 4759678, 4712877, 4666076, 4619275, 4572473, 4525672, 4478871, 4432070, 4385269, 4338468, 4291667, 4244866, 4198065, 4151264, 4104463, 4057661, 4010860, 3964059, 3917258, 3870457, 3823656, 3776855, 3730054, 3683253, 3636452, 3589651, 3542849, 3496048, 3449247, 3402446, 3355645, 3308844, 3262043, 3215242, 3168441, 3121640, 3074839, 3028037, 2981236, 2934435, 2887634, 2840833, 2794032, 2747231, 2700430, 2653629, 2606828, 2560027, 2513225, 2466424, 2419623, 2372822, 2326021, 2279220, 2232419, 2185618, 2138817, 2092016, 2045214, 1998413, 1951612, 1904811, 1858010, 1811209, 1764408, 1717607, 1670806, 1624005, 1577204, 1530402, 1483601, 1436800, 1389999, 1343198, 1296397, 1249596, 1202795, 1155994, 1109193, 1062392, 1015590, 968789, 921988, 875187, 828386, 781585, 734784, 687983, 641182, 594381, 547580, 500778, 453977, 407176, 360375, 313574, 266773, 219972, 173171, 126370, 79569, 32768, -14033, -60834, -107635, -154436, -201237, -248038, -294839, -341640, -388441, -435242, -482044, -528845, -575646, -622447, -669248, -716049, -762850, -809651, -856452, -903253, -950054, -996856, -1043657, -1090458, -1137259, -1184060, -1230861, -1277662, -1324463, -1371264, -1418065, -1464866, -1511668, -1558469, -1605270, -1652071, -1698872, -1745673, -1792474, -1839275, -1886076, -1932877, -1979678, -2026480, -2073281, -2120082, -2166883, -2213684, -2260485, -2307286, -2354087, -2400888, -2447689, -2494491, -2541292, -2588093, -2634894, -2681695, -2728496, -2775297, -2822098, -2868899, -2915700, -2962501, -3009303, -3056104, -3102905, -3149706, -3196507, -3243308, -3290109, -3336910, -3383711, -3430512, -3477313, -3524115, -3570916, -3617717, -3664518, -3711319, -3758120, -3804921, -3851722, -3898523, -3945324, -3992125, -4038927, -4085728, -4132529, -4179330, -4226131, -4272932, -4319733, -4366534, -4413335, -4460136, -4506937, -4553739, -4600540, -4647341, -4694142, -4740943, -4787744, -4834545, -4881346, -4928147, -4974948, -5021750, -5068551, -5115352, -5162153, -5208954, -5255755, -5302556, -5349357, -5396158, -5442959, -5489760, -5536562, -5583363, -5630164, -5676965, -5723766, -5770567, -5817368, -5864169, -5910970 }; static constexpr int16_t B_Cb[256] = { -226, -225, -223, -221, -219, -217, -216, -214, -212, -210, -209, -207, -205, -203, -202, -200, -198, -196, -194, -193, -191, -189, -187, -186, -184, -182, -180, -178, -177, -175, -173, -171, -170, -168, -166, -164, -163, -161, -159, -157, -155, -154, -152, -150, -148, -147, -145, -143, -141, -139, -138, -136, -134, -132, -131, -129, -127, -125, -124, -122, -120, -118, -116, -115, -113, -111, -109, -108, -106, -104, -102, -101, -99, -97, -95, -93, -92, -90, -88, -86, -85, -83, -81, -79, -77, -76, -74, -72, -70, -69, -67, -65, -63, -62, -60, -58, -56, -54, -53, -51, -49, -47, -46, -44, -42, -40, -38, -37, -35, -33, -31, -30, -28, -26, -24, -23, -21, -19, -17, -15, -14, -12, -10, -8, -7, -5, -3, -1, 0, 1, 3, 5, 7, 8, 10, 12, 14, 15, 17, 19, 21, 23, 24, 26, 28, 30, 31, 33, 35, 37, 38, 40, 42, 44, 46, 47, 49, 51, 53, 54, 56, 58, 60, 62, 63, 65, 67, 69, 70, 72, 74, 76, 77, 79, 81, 83, 85, 86, 88, 90, 92, 93, 95, 97, 99, 101, 102, 104, 106, 108, 109, 111, 113, 115, 116, 118, 120, 122, 124, 125, 127, 129, 131, 132, 134, 136, 138, 139, 141, 143, 145, 147, 148, 150, 152, 154, 155, 157, 159, 161, 163, 164, 166, 168, 170, 171, 173, 175, 177, 178, 180, 182, 184, 186, 187, 189, 191, 193, 194, 196, 198, 200, 202, 203, 205, 207, 209, 210, 212, 214, 216, 217, 219, 221, 223, 225 }; } // namespace cuslide::jpeg2k #endif // CUSLIDE_JPEG2K_COLOR_TABLE_H // clang-format on
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/jpeg2k/libopenjpeg.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_LIBOPENJPEG_H #define CUSLIDE_LIBOPENJPEG_H #include <cucim/io/device.h> namespace cuslide::jpeg2k { constexpr uint32_t kAperioJpeg2kYCbCr = 33003; // Jpeg 2000 with YCbCr format, possibly with a chroma subsampling of // 4:2:2 constexpr uint32_t kAperioJpeg2kRGB = 33005; // Jpeg 2000 with RGB format enum class ColorSpace : uint8_t { kUnspecified = 0, // not specified in the codestream kRGB = 1, // sRGB kGRAY = 2, // grayscale kSYCC = 3, // YUV kEYCC = 4, // e-YCC kCMYK = 5 // CMYK }; bool decode_libopenjpeg(int fd, unsigned char* jpeg_buf, uint64_t offset, uint64_t size, uint8_t** dest, uint64_t dest_nbytes, const cucim::io::Device& out_device, ColorSpace color_space); } // namespace cuslide::jpeg2k #endif // CUSLIDE_LIBOPENJPEG_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/tiff/ifd.h
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_IFD_H #define CUSLIDE_IFD_H #include "types.h" #include <memory> #include <vector> #include <cucim/concurrent/threadpool.h> #include <cucim/io/format/image_format.h> #include <cucim/io/device.h> #include <cucim/loader/thread_batch_data_loader.h> //#include <tiffio.h> namespace cuslide::tiff { // Forward declaration. class TIFF; class EXPORT_VISIBLE IFD : public std::enable_shared_from_this<IFD> { public: IFD(TIFF* tiff, uint16_t index, ifd_offset_t offset); ~IFD() = default; static bool read_region_tiles(const TIFF* tiff, const IFD* ifd, const int64_t* location, const int64_t location_index, const int64_t w, const int64_t h, void* raster, const cucim::io::Device& out_device, cucim::loader::ThreadBatchDataLoader* loader); static bool read_region_tiles_boundary(const TIFF* tiff, const IFD* ifd, const int64_t* location, const int64_t location_index, const int64_t w, const int64_t h, void* raster, const cucim::io::Device& out_device, cucim::loader::ThreadBatchDataLoader* loader); bool read(const TIFF* tiff, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data); uint32_t index() const; ifd_offset_t offset() const; std::string& software(); std::string& model(); std::string& image_description(); uint16_t resolution_unit() const; float x_resolution() const; float y_resolution() const; uint32_t width() const; uint32_t height() const; uint32_t tile_width() const; uint32_t tile_height() const; uint32_t rows_per_strip() const; uint32_t bits_per_sample() const; uint32_t samples_per_pixel() const; uint64_t subfile_type() const; uint16_t planar_config() const; uint16_t photometric() const; uint16_t compression() const; uint16_t predictor() const; uint16_t subifd_count() const; std::vector<uint64_t>& subifd_offsets(); uint32_t image_piece_count() const; const std::vector<uint64_t>& image_piece_offsets() const; const std::vector<uint64_t>& image_piece_bytecounts() const; size_t pixel_size_nbytes() const; size_t tile_raster_size_nbytes() const; // Hidden methods for benchmarking void write_offsets_(const char* file_path); // Make TIFF available to access private members of IFD friend class TIFF; private: TIFF* tiff_; // cannot use shared_ptr as IFD is created during the construction of TIFF using 'new' uint32_t ifd_index_ = 0; ifd_offset_t ifd_offset_ = 0; std::string software_; std::string model_; std::string image_description_; uint16_t resolution_unit_ = 1; // 1 = No absolute unit of measurement, 2 = Inch, 3 = Centimeter float x_resolution_ = 1.0f; float y_resolution_ = 1.0f; uint32_t flags_ = 0; uint32_t width_ = 0; uint32_t height_ = 0; uint32_t tile_width_ = 0; uint32_t tile_height_ = 0; uint32_t rows_per_strip_ = 0; uint32_t bits_per_sample_ = 0; uint32_t samples_per_pixel_ = 0; uint64_t subfile_type_ = 0; uint16_t planar_config_ = 0; uint16_t photometric_ = 0; uint16_t compression_ = 0; uint16_t predictor_ = 1; // 1: none, 2: horizontal differencing, 3: floating point predictor uint16_t subifd_count_ = 0; std::vector<uint64_t> subifd_offsets_; std::vector<uint8_t> jpegtable_; int32_t jpeg_color_space_ = 0; /// 0: JCS_UNKNOWN, 2: JCS_RGB, 3: JCS_YCbCr uint32_t image_piece_count_ = 0; std::vector<uint64_t> image_piece_offsets_; std::vector<uint64_t> image_piece_bytecounts_; uint64_t hash_value_ = 0; /// file hash including ifd index. /** * @brief Check if the current compression method is supported or not. */ bool is_compression_supported() const; /** * * Note: This method is called by the constructor of IFD and read() method so it is possible that the output of * 'is_read_optimizable()' could be changed during read() method if user set read configuration * after opening TIFF file. * @return */ bool is_read_optimizable() const; /** * @brief Check if the specified image format is supported or not. */ bool is_format_supported() const; }; } // namespace cuslide::tiff #endif // CUSLIDE_IFD_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/tiff/tiff.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_TIFF_H #define CUSLIDE_TIFF_H #include <cucim/filesystem/file_path.h> #include <cucim/filesystem/file_handle.h> #include <cucim/io/format/image_format.h> #include <cucim/macros/api_header.h> #include <cucim/memory/memory_manager.h> #include <cstdint> #include <fcntl.h> #include <map> #include <memory> #include <mutex> #include <vector> #include "ifd.h" #include "types.h" typedef struct tiff TIFF; namespace cuslide::tiff { /** * TIFF file handler class. * * This class doesn't use PImpl idiom for performance reasons and is not * intended to be used for subclassing. */ class EXPORT_VISIBLE TIFF : public std::enable_shared_from_this<TIFF> { public: TIFF(const cucim::filesystem::Path& file_path, int mode); TIFF(const cucim::filesystem::Path& file_path, int mode, uint64_t config); static std::shared_ptr<TIFF> open(const cucim::filesystem::Path& file_path, int mode); static std::shared_ptr<TIFF> open(const cucim::filesystem::Path& file_path, int mode, uint64_t config); void close(); void construct_ifds(); /** * Resolve vendor format and fix values for `associated_image_descs_` and `level_to_ifd_idx_. */ void resolve_vendor_format(); bool read(const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata = nullptr); bool read_associated_image(const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata); cucim::filesystem::Path file_path() const; std::shared_ptr<CuCIMFileHandle>& file_handle(); /// used for moving the ownership of the file handle to the caller. /// Do not use for the application -- it will return nullptr. ::TIFF* client() const; const std::vector<ifd_offset_t>& ifd_offsets() const; std::shared_ptr<IFD> ifd(size_t index) const; std::shared_ptr<IFD> level_ifd(size_t level_index) const; size_t ifd_count() const; size_t level_count() const; const std::map<std::string, AssociatedImageBufferDesc>& associated_images() const; size_t associated_image_count() const; bool is_big_endian() const; uint64_t read_config() const; bool is_in_read_config(uint64_t configs) const; void add_read_config(uint64_t configs); TiffType tiff_type(); std::string metadata(); ~TIFF(); static void* operator new(std::size_t sz); static void operator delete(void* ptr); // static void* operator new[](std::size_t sz); // static void operator delete(void* ptr, std::size_t sz); // static void operator delete[](void* ptr, std::size_t sz); // const values for read_configs_ static constexpr uint64_t kUseDirectJpegTurbo = 1; static constexpr uint64_t kUseLibTiff = 1 << 1; // Make IFD available to access private members of TIFF friend class IFD; private: void _populate_philips_tiff_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd); void _populate_aperio_svs_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd); cucim::filesystem::Path file_path_; /// Temporary shared file handle whose ownership would be transferred to CuImage through parser_open() std::shared_ptr<CuCIMFileHandle> file_handle_shared_; CuCIMFileHandle* file_handle_ = nullptr; ::TIFF* tiff_client_ = nullptr; std::vector<ifd_offset_t> ifd_offsets_; /// IFD offset for an index (IFD index) std::vector<std::shared_ptr<IFD>> ifds_; /// IFD object for an index (IFD index) std::vector<size_t> level_to_ifd_idx_; // note: we use std::map instead of std::unordered_map as # of associated_image would be usually less than 10. std::map<std::string, AssociatedImageBufferDesc> associated_images_; bool is_big_endian_ = false; /// if big endian uint8_t background_value_ = 0x00; /// background_value uint64_t read_config_ = 0; TiffType tiff_type_ = TiffType::Generic; void* metadata_ = nullptr; mutable std::once_flag slow_path_warning_flag_; }; } // namespace cuslide::tiff #endif // CUSLIDE_TIFF_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/tiff/ifd.cpp
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ifd.h" #include <sys/types.h> #include <unistd.h> #include <algorithm> #include <iostream> #include <random> #include <thread> #include <fmt/format.h> #include <tiffio.h> #include <tiffiop.h> // this is not included in the released library #include <turbojpeg.h> #include <cucim/codec/hash_function.h> #include <cucim/cuimage.h> #include <cucim/logger/timer.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> #include <cucim/util/cuda.h> #include "cuslide/deflate/deflate.h" #include "cuslide/jpeg/libjpeg_turbo.h" #include "cuslide/jpeg2k/libopenjpeg.h" #include "cuslide/loader/nvjpeg_processor.h" #include "cuslide/lzw/lzw.h" #include "cuslide/raw/raw.h" #include "tiff.h" namespace cuslide::tiff { IFD::IFD(TIFF* tiff, uint16_t index, ifd_offset_t offset) : tiff_(tiff), ifd_index_(index), ifd_offset_(offset) { PROF_SCOPED_RANGE(PROF_EVENT(ifd_ifd)); auto tif = tiff->client(); char* software_char_ptr = nullptr; char* model_char_ptr = nullptr; // TODO: error handling TIFFGetField(tif, TIFFTAG_SOFTWARE, &software_char_ptr); software_ = std::string(software_char_ptr ? software_char_ptr : ""); TIFFGetField(tif, TIFFTAG_MODEL, &model_char_ptr); model_ = std::string(model_char_ptr ? model_char_ptr : ""); TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &model_char_ptr); image_description_ = std::string(model_char_ptr ? model_char_ptr : ""); TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &resolution_unit_); TIFFGetField(tif, TIFFTAG_XRESOLUTION, &x_resolution_); TIFFGetField(tif, TIFFTAG_YRESOLUTION, &y_resolution_); TIFFDirectory& tif_dir = tif->tif_dir; flags_ = tif->tif_flags; width_ = tif_dir.td_imagewidth; height_ = tif_dir.td_imagelength; if ((flags_ & TIFF_ISTILED) != 0) { tile_width_ = tif_dir.td_tilewidth; tile_height_ = tif_dir.td_tilelength; } else { rows_per_strip_ = tif_dir.td_rowsperstrip; } bits_per_sample_ = tif_dir.td_bitspersample; samples_per_pixel_ = tif_dir.td_samplesperpixel; subfile_type_ = tif_dir.td_subfiletype; planar_config_ = tif_dir.td_planarconfig; photometric_ = tif_dir.td_photometric; compression_ = tif_dir.td_compression; TIFFGetField(tif, TIFFTAG_PREDICTOR, &predictor_); subifd_count_ = tif_dir.td_nsubifd; uint64_t* subifd_offsets = tif_dir.td_subifd; if (subifd_count_) { subifd_offsets_.resize(subifd_count_); subifd_offsets_.insert(subifd_offsets_.end(), &subifd_offsets[0], &subifd_offsets[subifd_count_]); } if (compression_ == COMPRESSION_JPEG) { uint8_t* jpegtable_data = nullptr; uint32_t jpegtable_count = 0; TIFFGetField(tif, TIFFTAG_JPEGTABLES, &jpegtable_count, &jpegtable_data); jpegtable_.reserve(jpegtable_count); jpegtable_.insert(jpegtable_.end(), jpegtable_data, jpegtable_data + jpegtable_count); if (photometric_ == PHOTOMETRIC_RGB) { jpeg_color_space_ = 2; // JCS_RGB } else if (photometric_ == PHOTOMETRIC_YCBCR) { jpeg_color_space_ = 3; // JCS_YCbCr } } image_piece_count_ = tif_dir.td_stripoffset_entry.tdir_count; image_piece_offsets_.reserve(image_piece_count_); uint64* td_stripoffset_p = tif_dir.td_stripoffset_p; uint64* td_stripbytecount_p = tif_dir.td_stripbytecount_p; // Copy data to vector image_piece_offsets_.insert(image_piece_offsets_.end(), &td_stripoffset_p[0], &td_stripoffset_p[image_piece_count_]); image_piece_bytecounts_.insert( image_piece_bytecounts_.end(), &td_stripbytecount_p[0], &td_stripbytecount_p[image_piece_count_]); // Calculate hash value with IFD index hash_value_ = tiff->file_handle_->hash_value ^ cucim::codec::splitmix64(index); // TIFFPrintDirectory(tif, stdout, TIFFPRINT_STRIPS); } bool IFD::read(const TIFF* tiff, const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data) { PROF_SCOPED_RANGE(PROF_EVENT(ifd_read)); ::TIFF* tif = tiff->tiff_client_; uint16_t ifd_index = ifd_index_; std::string device_name(request->device); if (request->shm_name) { device_name = device_name + fmt::format("[{}]", request->shm_name); // TODO: check performance } cucim::io::Device out_device(device_name); int64_t sx = request->location[0]; int64_t sy = request->location[1]; uint32_t batch_size = request->batch_size; int64_t w = request->size[0]; int64_t h = request->size[1]; int32_t n_ch = samples_per_pixel_; // number of channels int ndim = 3; size_t raster_size = w * h * samples_per_pixel_; void* raster = nullptr; auto raster_type = cucim::io::DeviceType::kCPU; DLTensor* out_buf = request->buf; bool is_buf_available = out_buf && out_buf->data; if (is_buf_available) { // TODO: memory size check if out_buf->data has high-enough memory (>= tjBufSize()) raster = out_buf->data; } if (is_read_optimizable()) { if (batch_size > 1) { ndim = 4; } int64_t* location = request->location; uint64_t location_len = request->location_len; const uint32_t num_workers = request->num_workers; const bool drop_last = request->drop_last; uint32_t prefetch_factor = request->prefetch_factor; const bool shuffle = request->shuffle; const uint64_t seed = request->seed; if (num_workers == 0 && location_len > 1) { throw std::runtime_error("Cannot read multiple locations with zero workers!"); } // Shuffle data if (shuffle) { auto rng = std::default_random_engine{ seed }; struct position { int64_t x; int64_t y; }; std::shuffle(reinterpret_cast<position*>(&location[0]), reinterpret_cast<position*>(&location[location_len * 2]), rng); } // Adjust location length based on 'drop_last' const uint32_t remaining_len = location_len % batch_size; if (drop_last) { location_len -= remaining_len; } // Do not use prefetch if the image is too small if (1 + prefetch_factor > location_len) { prefetch_factor = location_len - 1; } size_t one_raster_size = raster_size; raster_size *= batch_size; const IFD* ifd = this; if (location_len > 1 || batch_size > 1 || num_workers > 0) { // Reconstruct location std::unique_ptr<std::vector<int64_t>>* location_unique = reinterpret_cast<std::unique_ptr<std::vector<int64_t>>*>(request->location_unique); std::unique_ptr<std::vector<int64_t>> request_location = std::move(*location_unique); delete location_unique; // Reconstruct size std::unique_ptr<std::vector<int64_t>>* size_unique = reinterpret_cast<std::unique_ptr<std::vector<int64_t>>*>(request->size_unique); std::unique_ptr<std::vector<int64_t>> request_size = std::move(*size_unique); delete size_unique; auto load_func = [tiff, ifd, location, w, h, out_device]( cucim::loader::ThreadBatchDataLoader* loader_ptr, uint64_t location_index) { uint8_t* raster_ptr = loader_ptr->raster_pointer(location_index); if (!read_region_tiles(tiff, ifd, location, location_index, w, h, raster_ptr, out_device, loader_ptr)) { fmt::print(stderr, "[Error] Failed to read region!\n"); } }; uint32_t maximum_tile_count = 0; std::unique_ptr<cucim::loader::BatchDataProcessor> batch_processor; // Set raster_type to CUDA because loader will handle this with nvjpeg if (out_device.type() == cucim::io::DeviceType::kCUDA) { raster_type = cucim::io::DeviceType::kCUDA; // The maximal number of tiles (x-axis) overapped with the given patch uint32_t tile_across_count = std::min(static_cast<uint64_t>(ifd->width_) + (ifd->tile_width_ - 1), static_cast<uint64_t>(w) + (ifd->tile_width_ - 1)) / ifd->tile_width_ + 1; // The maximal number of tiles (y-axis) overapped with the given patch uint32_t tile_down_count = std::min(static_cast<uint64_t>(ifd->height_) + (ifd->tile_height_ - 1), static_cast<uint64_t>(h) + (ifd->tile_height_ - 1)) / ifd->tile_height_ + 1; // The maximal number of possible tiles (# of tasks) to load for the given image batch maximum_tile_count = tile_across_count * tile_down_count * batch_size; // Create NvJpegProcessor auto& jpegtable = ifd->jpegtable_; const void* jpegtable_data = jpegtable.data(); uint32_t jpegtable_size = jpegtable.size(); auto nvjpeg_processor = std::make_unique<cuslide::loader::NvJpegProcessor>( tiff->file_handle_, ifd, request_location->data(), request_size->data(), location_len, batch_size, maximum_tile_count, static_cast<const uint8_t*>(jpegtable_data), jpegtable_size); // Update prefetch_factor prefetch_factor = nvjpeg_processor->preferred_loader_prefetch_factor(); batch_processor = std::move(nvjpeg_processor); } auto loader = std::make_unique<cucim::loader::ThreadBatchDataLoader>( load_func, std::move(batch_processor), out_device, std::move(request_location), std::move(request_size), location_len, one_raster_size, batch_size, prefetch_factor, num_workers); const uint32_t load_size = std::min(static_cast<uint64_t>(batch_size) * (1 + prefetch_factor), location_len); loader->request(load_size); // If it reads entire image with multi threads (using loader), fetch the next item. if (location_len == 1 && batch_size == 1) { raster = loader->next_data(); } out_image_data->loader = loader.release(); // set loader to out_image_data } else { if (!raster) { raster = cucim_malloc(one_raster_size); } if (!read_region_tiles(tiff, ifd, location, 0, w, h, raster, out_device, nullptr)) { fmt::print(stderr, "[Error] Failed to read region!\n"); } } } else { PROF_SCOPED_RANGE(PROF_EVENT(ifd_read_slowpath)); // Print a warning message for the slow path std::call_once( tiff->slow_path_warning_flag_, [](const std::string& file_path) { fmt::print( stderr, "[Warning] Loading image('{}') with a slow-path. The pixel format of the loaded image would be RGBA (4 channels) instead of RGB!\n", file_path); }, tiff->file_path()); // Handle out-of-boundary case int64_t ex = sx + w - 1; int64_t ey = sy + h - 1; if (sx < 0 || sy < 0 || sx >= width_ || sy >= height_ || ex < 0 || ey < 0 || ex >= width_ || ey >= height_) { throw std::invalid_argument(fmt::format("Cannot handle the out-of-boundary cases.")); } // Check if the image format is supported or not if (!is_format_supported()) { throw std::runtime_error(fmt::format( "This format (compression: {}, sample_per_pixel: {}, planar_config: {}, photometric: {}) is not supported yet!.", compression_, samples_per_pixel_, planar_config_, photometric_)); } if (tif->tif_curdir != ifd_index) { TIFFSetDirectory(tif, ifd_index); } // RGBA -> 4 channels n_ch = 4; char emsg[1024]; if (TIFFRGBAImageOK(tif, emsg)) { TIFFRGBAImage img; if (TIFFRGBAImageBegin(&img, tif, -1, emsg)) { size_t npixels; npixels = w * h; raster_size = npixels * 4; if (!raster) { raster = cucim_malloc(raster_size); } img.col_offset = sx; img.row_offset = sy; img.req_orientation = ORIENTATION_TOPLEFT; if (raster != nullptr) { if (!TIFFRGBAImageGet(&img, (uint32_t*)raster, w, h)) { memset(raster, 0, raster_size); } } } else { throw std::runtime_error(fmt::format( "This format (compression: {}, sample_per_pixel: {}, planar_config: {}, photometric: {}) is not supported yet!: {}", compression_, samples_per_pixel_, planar_config_, photometric_, emsg)); } TIFFRGBAImageEnd(&img); } else { throw std::runtime_error(fmt::format( "This format (compression: {}, sample_per_pixel: {}, planar_config: {}, photometric: {}) is not supported yet!: {}", compression_, samples_per_pixel_, planar_config_, photometric_, emsg)); } } int64_t* shape = static_cast<int64_t*>(cucim_malloc(sizeof(int64_t) * ndim)); if (ndim == 3) { shape[0] = h; shape[1] = w; shape[2] = n_ch; } else // ndim == 4 { shape[0] = batch_size; shape[1] = h; shape[2] = w; shape[3] = n_ch; } // Copy the raster memory and free it if needed. if (!is_buf_available && raster && raster_type == cucim::io::DeviceType::kCPU) { cucim::memory::move_raster_from_host(&raster, raster_size, out_device); } auto& out_image_container = out_image_data->container; out_image_container.data = raster; out_image_container.device = DLDevice{ static_cast<DLDeviceType>(out_device.type()), out_device.index() }; out_image_container.ndim = ndim; out_image_container.dtype = metadata->dtype; out_image_container.shape = shape; out_image_container.strides = nullptr; // Tensor is compact and row-majored out_image_container.byte_offset = 0; auto& shm_name = out_device.shm_name(); size_t shm_name_len = shm_name.size(); if (shm_name_len != 0) { out_image_data->shm_name = static_cast<char*>(cucim_malloc(shm_name_len + 1)); memcpy(out_image_data->shm_name, shm_name.c_str(), shm_name_len + 1); } else { out_image_data->shm_name = nullptr; } return true; } uint32_t IFD::index() const { return ifd_index_; } ifd_offset_t IFD::offset() const { return ifd_offset_; } std::string& IFD::software() { return software_; } std::string& IFD::model() { return model_; } std::string& IFD::image_description() { return image_description_; } uint16_t IFD::resolution_unit() const { return resolution_unit_; } float IFD::x_resolution() const { return x_resolution_; } float IFD::y_resolution() const { return y_resolution_; } uint32_t IFD::width() const { return width_; } uint32_t IFD::height() const { return height_; } uint32_t IFD::tile_width() const { return tile_width_; } uint32_t IFD::tile_height() const { return tile_height_; } uint32_t IFD::rows_per_strip() const { return rows_per_strip_; } uint32_t IFD::bits_per_sample() const { return bits_per_sample_; } uint32_t IFD::samples_per_pixel() const { return samples_per_pixel_; } uint64_t IFD::subfile_type() const { return subfile_type_; } uint16_t IFD::planar_config() const { return planar_config_; } uint16_t IFD::photometric() const { return photometric_; } uint16_t IFD::compression() const { return compression_; } uint16_t IFD::predictor() const { return predictor_; } uint16_t IFD::subifd_count() const { return subifd_count_; } std::vector<uint64_t>& IFD::subifd_offsets() { return subifd_offsets_; } uint32_t IFD::image_piece_count() const { return image_piece_count_; } const std::vector<uint64_t>& IFD::image_piece_offsets() const { return image_piece_offsets_; } const std::vector<uint64_t>& IFD::image_piece_bytecounts() const { return image_piece_bytecounts_; } size_t IFD::pixel_size_nbytes() const { const int pixel_format = TJPF_RGB; // TODO: support other pixel format const int nbytes = tjPixelSize[pixel_format]; return nbytes; } size_t IFD::tile_raster_size_nbytes() const { const size_t nbytes = tile_width_ * tile_height_ * pixel_size_nbytes(); return nbytes; } bool IFD::is_compression_supported() const { switch (compression_) { case COMPRESSION_NONE: case COMPRESSION_JPEG: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: case cuslide::jpeg2k::kAperioJpeg2kYCbCr: // 33003: Jpeg 2000 with YCbCr format, possibly with a chroma subsampling // of 4:2:2 case cuslide::jpeg2k::kAperioJpeg2kRGB: // 33005: Jpeg 2000 with RGB case COMPRESSION_LZW: return true; default: return false; } } bool IFD::is_read_optimizable() const { return is_compression_supported() && bits_per_sample_ == 8 && samples_per_pixel_ == 3 && (tile_width_ != 0 && tile_height_ != 0) && planar_config_ == PLANARCONFIG_CONTIG && (photometric_ == PHOTOMETRIC_RGB || photometric_ == PHOTOMETRIC_YCBCR) && !tiff_->is_in_read_config(TIFF::kUseLibTiff); } bool IFD::is_format_supported() const { return is_compression_supported(); } bool IFD::read_region_tiles(const TIFF* tiff, const IFD* ifd, const int64_t* location, const int64_t location_index, const int64_t w, const int64_t h, void* raster, const cucim::io::Device& out_device, cucim::loader::ThreadBatchDataLoader* loader) { PROF_SCOPED_RANGE(PROF_EVENT(ifd_read_region_tiles)); // Reference code: https://github.com/libjpeg-turbo/libjpeg-turbo/blob/master/tjexample.c int64_t sx = location[location_index * 2]; int64_t sy = location[location_index * 2 + 1]; int64_t ex = sx + w - 1; int64_t ey = sy + h - 1; uint32_t width = ifd->width_; uint32_t height = ifd->height_; // Handle out-of-boundary case if (sx < 0 || sy < 0 || sx >= width || sy >= height || ex < 0 || ey < 0 || ex >= width || ey >= height) { return read_region_tiles_boundary(tiff, ifd, location, location_index, w, h, raster, out_device, loader); } cucim::cache::ImageCache& image_cache = cucim::CuImage::cache_manager().cache(); cucim::cache::CacheType cache_type = image_cache.type(); uint8_t background_value = tiff->background_value_; uint16_t compression_method = ifd->compression_; int jpeg_color_space = ifd->jpeg_color_space_; int predictor = ifd->predictor_; // TODO: revert this once we can get RGB data instead of RGBA uint32_t samples_per_pixel = 3; // ifd->samples_per_pixel(); const void* jpegtable_data = ifd->jpegtable_.data(); uint32_t jpegtable_count = ifd->jpegtable_.size(); uint32_t tw = ifd->tile_width_; uint32_t th = ifd->tile_height_; uint32_t offset_sx = static_cast<uint32_t>(sx / tw); // x-axis start offset for the requested region in the ifd tile // array as grid uint32_t offset_ex = static_cast<uint32_t>(ex / tw); // x-axis end offset for the requested region in the ifd tile // array as grid uint32_t offset_sy = static_cast<uint32_t>(sy / th); // y-axis start offset for the requested region in the ifd tile // array as grid uint32_t offset_ey = static_cast<uint32_t>(ey / th); // y-axis end offset for the requested region in the ifd tile // array as grid uint32_t pixel_offset_sx = static_cast<uint32_t>(sx % tw); uint32_t pixel_offset_ex = static_cast<uint32_t>(ex % tw); uint32_t pixel_offset_sy = static_cast<uint32_t>(sy % th); uint32_t pixel_offset_ey = static_cast<uint32_t>(ey % th); uint32_t stride_y = width / tw + !!(width % tw); // # of tiles in a row(y) in the ifd tile array as grid uint32_t start_index_y = offset_sy * stride_y; uint32_t end_index_y = offset_ey * stride_y; const size_t tile_raster_nbytes = ifd->tile_raster_size_nbytes(); int tiff_file = tiff->file_handle_->fd; uint64_t ifd_hash_value = ifd->hash_value_; uint32_t dest_pixel_step_y = w * samples_per_pixel; uint32_t nbytes_tw = tw * samples_per_pixel; auto dest_start_ptr = static_cast<uint8_t*>(raster); // TODO: Current implementation doesn't consider endianness so need to consider later // TODO: Consider tile's depth tag. for (uint32_t index_y = start_index_y; index_y <= end_index_y; index_y += stride_y) { uint32_t tile_pixel_offset_sy = (index_y == start_index_y) ? pixel_offset_sy : 0; uint32_t tile_pixel_offset_ey = (index_y == end_index_y) ? pixel_offset_ey : (th - 1); uint32_t dest_pixel_offset_len_y = tile_pixel_offset_ey - tile_pixel_offset_sy + 1; uint32_t dest_pixel_index_x = 0; uint32_t index = index_y + offset_sx; for (uint32_t offset_x = offset_sx; offset_x <= offset_ex; ++offset_x, ++index) { PROF_SCOPED_RANGE(PROF_EVENT_P(ifd_read_region_tiles_iter, index)); auto tiledata_offset = static_cast<uint64_t>(ifd->image_piece_offsets_[index]); auto tiledata_size = static_cast<uint64_t>(ifd->image_piece_bytecounts_[index]); // Calculate a simple hash value for the tile index uint64_t index_hash = ifd_hash_value ^ (static_cast<uint64_t>(index) | (static_cast<uint64_t>(index) << 32)); uint32_t tile_pixel_offset_x = (offset_x == offset_sx) ? pixel_offset_sx : 0; uint32_t nbytes_tile_pixel_size_x = (offset_x == offset_ex) ? (pixel_offset_ex - tile_pixel_offset_x + 1) * samples_per_pixel : (tw - tile_pixel_offset_x) * samples_per_pixel; auto decode_func = [=, &image_cache]() { PROF_SCOPED_RANGE(PROF_EVENT_P(ifd_read_region_tiles_task, index_hash)); uint32_t nbytes_tile_index = (tile_pixel_offset_sy * tw + tile_pixel_offset_x) * samples_per_pixel; uint32_t dest_pixel_index = dest_pixel_index_x; uint8_t* tile_data = nullptr; if (tiledata_size > 0) { std::unique_ptr<uint8_t, decltype(cucim_free)*> tile_raster = std::unique_ptr<uint8_t, decltype(cucim_free)*>(nullptr, cucim_free); if (loader && loader->batch_data_processor()) { switch (compression_method) { case COMPRESSION_JPEG: break; default: throw std::runtime_error("Unsupported compression method"); } auto value = loader->wait_for_processing(index); if (!value) // if shutdown { return; } tile_data = static_cast<uint8_t*>(value->data); cudaError_t cuda_status; CUDA_ERROR(cudaMemcpy2D(dest_start_ptr + dest_pixel_index, dest_pixel_step_y, tile_data + nbytes_tile_index, nbytes_tw, nbytes_tile_pixel_size_x, tile_pixel_offset_ey - tile_pixel_offset_sy + 1, cudaMemcpyDeviceToDevice)); } else { auto key = image_cache.create_key(ifd_hash_value, index); image_cache.lock(index_hash); auto value = image_cache.find(key); if (value) { image_cache.unlock(index_hash); tile_data = static_cast<uint8_t*>(value->data); } else { // Lifetime of tile_data is same with `value` // : do not access this data when `value` is not accessible. if (cache_type != cucim::cache::CacheType::kNoCache) { tile_data = static_cast<uint8_t*>(image_cache.allocate(tile_raster_nbytes)); } else { // Allocate temporary buffer for tile data tile_raster = std::unique_ptr<uint8_t, decltype(cucim_free)*>( reinterpret_cast<uint8_t*>(cucim_malloc(tile_raster_nbytes)), cucim_free); tile_data = tile_raster.get(); } { PROF_SCOPED_RANGE(PROF_EVENT(ifd_decompression)); switch (compression_method) { case COMPRESSION_NONE: cuslide::raw::decode_raw(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); break; case COMPRESSION_JPEG: cuslide::jpeg::decode_libjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, jpegtable_data, jpegtable_count, &tile_data, out_device, jpeg_color_space); break; case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: cuslide::deflate::decode_deflate(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); break; case cuslide::jpeg2k::kAperioJpeg2kYCbCr: // 33003 cuslide::jpeg2k::decode_libopenjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device, cuslide::jpeg2k::ColorSpace::kSYCC); break; case cuslide::jpeg2k::kAperioJpeg2kRGB: // 33005 cuslide::jpeg2k::decode_libopenjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device, cuslide::jpeg2k::ColorSpace::kRGB); break; case COMPRESSION_LZW: cuslide::lzw::decode_lzw(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); // Apply unpredictor // 1: none, 2: horizontal differencing, 3: floating point predictor // https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf if (predictor == 2) { cuslide::lzw::horAcc8(tile_data, tile_raster_nbytes, nbytes_tw); } break; default: throw std::runtime_error("Unsupported compression method"); } } value = image_cache.create_value(tile_data, tile_raster_nbytes); image_cache.insert(key, value); image_cache.unlock(index_hash); } for (uint32_t ty = tile_pixel_offset_sy; ty <= tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { memcpy(dest_start_ptr + dest_pixel_index, tile_data + nbytes_tile_index, nbytes_tile_pixel_size_x); } } } else { if (out_device.type() == cucim::io::DeviceType::kCPU) { for (uint32_t ty = tile_pixel_offset_sy; ty <= tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { // Set background value such as (255,255,255) memset(dest_start_ptr + dest_pixel_index, background_value, nbytes_tile_pixel_size_x); } } else { cudaError_t cuda_status; CUDA_ERROR(cudaMemset2D(dest_start_ptr + dest_pixel_index, dest_pixel_step_y, background_value, nbytes_tile_pixel_size_x, tile_pixel_offset_ey - tile_pixel_offset_sy + 1)); } } }; if (loader && *loader) { loader->enqueue(std::move(decode_func), cucim::loader::TileInfo{ location_index, index, tiledata_offset, tiledata_size }); } else { decode_func(); } dest_pixel_index_x += nbytes_tile_pixel_size_x; } dest_start_ptr += dest_pixel_step_y * dest_pixel_offset_len_y; } return true; } bool IFD::read_region_tiles_boundary(const TIFF* tiff, const IFD* ifd, const int64_t* location, const int64_t location_index, const int64_t w, const int64_t h, void* raster, const cucim::io::Device& out_device, cucim::loader::ThreadBatchDataLoader* loader) { PROF_SCOPED_RANGE(PROF_EVENT(ifd_read_region_tiles_boundary)); (void)out_device; // Reference code: https://github.com/libjpeg-turbo/libjpeg-turbo/blob/master/tjexample.c int64_t sx = location[location_index * 2]; int64_t sy = location[location_index * 2 + 1]; uint8_t background_value = tiff->background_value_; uint16_t compression_method = ifd->compression_; int jpeg_color_space = ifd->jpeg_color_space_; int predictor = ifd->predictor_; int64_t ex = sx + w - 1; int64_t ey = sy + h - 1; uint32_t width = ifd->width_; uint32_t height = ifd->height_; // Memory for tile_raster would be manually allocated here, instead of using decode_libjpeg(). // Need to free the manually. Usually it is set to nullptr and memory is created by decode_libjpeg() by using // tjAlloc() (Also need to free with tjFree() after use. See the documentation of tjAlloc() for the detail.) const int pixel_size_nbytes = ifd->pixel_size_nbytes(); auto dest_start_ptr = static_cast<uint8_t*>(raster); bool is_out_of_image = (ex < 0 || width <= sx || ey < 0 || height <= sy); if (is_out_of_image) { // Fill background color(255,255,255) and return memset(dest_start_ptr, background_value, w * h * pixel_size_nbytes); return true; } cucim::cache::ImageCache& image_cache = cucim::CuImage::cache_manager().cache(); cucim::cache::CacheType cache_type = image_cache.type(); uint32_t tw = ifd->tile_width_; uint32_t th = ifd->tile_height_; const size_t tile_raster_nbytes = tw * th * pixel_size_nbytes; // TODO: revert this once we can get RGB data instead of RGBA uint32_t samples_per_pixel = 3; // ifd->samples_per_pixel(); const void* jpegtable_data = ifd->jpegtable_.data(); uint32_t jpegtable_count = ifd->jpegtable_.size(); bool sx_in_range = (sx >= 0 && sx < width); bool ex_in_range = (ex >= 0 && ex < width); bool sy_in_range = (sy >= 0 && sy < height); bool ey_in_range = (ey >= 0 && ey < height); int64_t offset_boundary_x = (static_cast<int64_t>(width) - 1) / tw; int64_t offset_boundary_y = (static_cast<int64_t>(height) - 1) / th; int64_t offset_sx = sx / tw; // x-axis start offset for the requested region in the // ifd tile array as grid int64_t offset_ex = ex / tw; // x-axis end offset for the requested region in the // ifd tile array as grid int64_t offset_sy = sy / th; // y-axis start offset for the requested region in the // ifd tile array as grid int64_t offset_ey = ey / th; // y-axis end offset for the requested region in the // ifd tile array as grid int64_t pixel_offset_sx = (sx % tw); int64_t pixel_offset_ex = (ex % tw); int64_t pixel_offset_sy = (sy % th); int64_t pixel_offset_ey = (ey % th); int64_t pixel_offset_boundary_x = ((width - 1) % tw); int64_t pixel_offset_boundary_y = ((height - 1) % th); // Make sure that division and modulo has same value with Python's one (e.g., making -1 / 3 == -1 instead of 0) if (pixel_offset_sx < 0) { pixel_offset_sx += tw; --offset_sx; } if (pixel_offset_ex < 0) { pixel_offset_ex += tw; --offset_ex; } if (pixel_offset_sy < 0) { pixel_offset_sy += th; --offset_sy; } if (pixel_offset_ey < 0) { pixel_offset_ey += th; --offset_ey; } int64_t offset_min_x = sx_in_range ? offset_sx : 0; int64_t offset_max_x = ex_in_range ? offset_ex : offset_boundary_x; int64_t offset_min_y = sy_in_range ? offset_sy : 0; int64_t offset_max_y = ey_in_range ? offset_ey : offset_boundary_y; uint32_t stride_y = width / tw + !!(width % tw); // # of tiles in a row(y) in the ifd tile array as grid int64_t start_index_y = offset_sy * stride_y; int64_t start_index_min_y = offset_min_y * stride_y; int64_t end_index_y = offset_ey * stride_y; int64_t end_index_max_y = offset_max_y * stride_y; int64_t boundary_index_y = offset_boundary_y * stride_y; int tiff_file = tiff->file_handle_->fd; uint64_t ifd_hash_value = ifd->hash_value_; uint32_t dest_pixel_step_y = w * samples_per_pixel; uint32_t nbytes_tw = tw * samples_per_pixel; // TODO: Current implementation doesn't consider endianness so need to consider later // TODO: Consider tile's depth tag. // TODO: update the type of variables (index, index_y) : other function uses uint32_t for (int64_t index_y = start_index_y; index_y <= end_index_y; index_y += stride_y) { uint32_t tile_pixel_offset_sy = (index_y == start_index_y) ? pixel_offset_sy : 0; uint32_t tile_pixel_offset_ey = (index_y == end_index_y) ? pixel_offset_ey : (th - 1); uint32_t dest_pixel_offset_len_y = tile_pixel_offset_ey - tile_pixel_offset_sy + 1; uint32_t dest_pixel_index_x = 0; int64_t index = index_y + offset_sx; for (int64_t offset_x = offset_sx; offset_x <= offset_ex; ++offset_x, ++index) { PROF_SCOPED_RANGE(PROF_EVENT_P(ifd_read_region_tiles_boundary_iter, index)); uint64_t tiledata_offset = 0; uint64_t tiledata_size = 0; // Calculate a simple hash value for the tile index uint64_t index_hash = ifd_hash_value ^ (static_cast<uint64_t>(index) | (static_cast<uint64_t>(index) << 32)); if (offset_x >= offset_min_x && offset_x <= offset_max_x && index_y >= start_index_min_y && index_y <= end_index_max_y) { tiledata_offset = static_cast<uint64_t>(ifd->image_piece_offsets_[index]); tiledata_size = static_cast<uint64_t>(ifd->image_piece_bytecounts_[index]); } uint32_t tile_pixel_offset_x = (offset_x == offset_sx) ? pixel_offset_sx : 0; uint32_t nbytes_tile_pixel_size_x = (offset_x == offset_ex) ? (pixel_offset_ex - tile_pixel_offset_x + 1) * samples_per_pixel : (tw - tile_pixel_offset_x) * samples_per_pixel; uint32_t nbytes_tile_index_orig = (tile_pixel_offset_sy * tw + tile_pixel_offset_x) * samples_per_pixel; uint32_t dest_pixel_index_orig = dest_pixel_index_x; auto decode_func = [=, &image_cache]() { PROF_SCOPED_RANGE(PROF_EVENT_P(ifd_read_region_tiles_boundary_task, index_hash)); uint32_t nbytes_tile_index = nbytes_tile_index_orig; uint32_t dest_pixel_index = dest_pixel_index_orig; if (tiledata_size > 0) { bool copy_partial = false; uint32_t fixed_nbytes_tile_pixel_size_x = nbytes_tile_pixel_size_x; uint32_t fixed_tile_pixel_offset_ey = tile_pixel_offset_ey; if (offset_x == offset_boundary_x) { copy_partial = true; if (offset_x != offset_ex) { fixed_nbytes_tile_pixel_size_x = (pixel_offset_boundary_x - tile_pixel_offset_x + 1) * samples_per_pixel; } else { fixed_nbytes_tile_pixel_size_x = (std::min(pixel_offset_boundary_x, pixel_offset_ex) - tile_pixel_offset_x + 1) * samples_per_pixel; } } if (index_y == boundary_index_y) { copy_partial = true; if (index_y != end_index_y) { fixed_tile_pixel_offset_ey = pixel_offset_boundary_y; } else { fixed_tile_pixel_offset_ey = std::min(pixel_offset_boundary_y, pixel_offset_ey); } } uint8_t* tile_data = nullptr; std::unique_ptr<uint8_t, decltype(cucim_free)*> tile_raster = std::unique_ptr<uint8_t, decltype(cucim_free)*>(nullptr, cucim_free); if (loader && loader->batch_data_processor()) { switch (compression_method) { case COMPRESSION_JPEG: break; default: throw std::runtime_error("Unsupported compression method"); } auto value = loader->wait_for_processing(index); if (!value) // if shutdown { return; } tile_data = static_cast<uint8_t*>(value->data); cudaError_t cuda_status; if (copy_partial) { uint32_t fill_gap_x = nbytes_tile_pixel_size_x - fixed_nbytes_tile_pixel_size_x; // Fill original, then fill white for remaining if (fill_gap_x > 0) { CUDA_ERROR(cudaMemcpy2D( dest_start_ptr + dest_pixel_index, dest_pixel_step_y, tile_data + nbytes_tile_index, nbytes_tw, fixed_nbytes_tile_pixel_size_x, fixed_tile_pixel_offset_ey - tile_pixel_offset_sy + 1, cudaMemcpyDeviceToDevice)); CUDA_ERROR(cudaMemset2D(dest_start_ptr + dest_pixel_index + fixed_nbytes_tile_pixel_size_x, dest_pixel_step_y, background_value, fill_gap_x, fixed_tile_pixel_offset_ey - tile_pixel_offset_sy + 1)); dest_pixel_index += dest_pixel_step_y * (fixed_tile_pixel_offset_ey - tile_pixel_offset_sy + 1); } else { CUDA_ERROR(cudaMemcpy2D( dest_start_ptr + dest_pixel_index, dest_pixel_step_y, tile_data + nbytes_tile_index, nbytes_tw, fixed_nbytes_tile_pixel_size_x, fixed_tile_pixel_offset_ey - tile_pixel_offset_sy + 1, cudaMemcpyDeviceToDevice)); dest_pixel_index += dest_pixel_step_y * (fixed_tile_pixel_offset_ey - tile_pixel_offset_sy + 1); } CUDA_ERROR(cudaMemset2D(dest_start_ptr + dest_pixel_index, dest_pixel_step_y, background_value, nbytes_tile_pixel_size_x, tile_pixel_offset_ey - (fixed_tile_pixel_offset_ey + 1) + 1)); } else { CUDA_ERROR(cudaMemcpy2D(dest_start_ptr + dest_pixel_index, dest_pixel_step_y, tile_data + nbytes_tile_index, nbytes_tw, nbytes_tile_pixel_size_x, tile_pixel_offset_ey - tile_pixel_offset_sy + 1, cudaMemcpyDeviceToDevice)); } } else { auto key = image_cache.create_key(ifd_hash_value, index); image_cache.lock(index_hash); auto value = image_cache.find(key); if (value) { image_cache.unlock(index_hash); tile_data = static_cast<uint8_t*>(value->data); } else { // Lifetime of tile_data is same with `value` // : do not access this data when `value` is not accessible. if (cache_type != cucim::cache::CacheType::kNoCache) { tile_data = static_cast<uint8_t*>(image_cache.allocate(tile_raster_nbytes)); } else { // Allocate temporary buffer for tile data tile_raster = std::unique_ptr<uint8_t, decltype(cucim_free)*>( reinterpret_cast<uint8_t*>(cucim_malloc(tile_raster_nbytes)), cucim_free); tile_data = tile_raster.get(); } { PROF_SCOPED_RANGE(PROF_EVENT(ifd_decompression)); switch (compression_method) { case COMPRESSION_NONE: cuslide::raw::decode_raw(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); break; case COMPRESSION_JPEG: cuslide::jpeg::decode_libjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, jpegtable_data, jpegtable_count, &tile_data, out_device, jpeg_color_space); break; case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: cuslide::deflate::decode_deflate(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); break; case cuslide::jpeg2k::kAperioJpeg2kYCbCr: // 33003 cuslide::jpeg2k::decode_libopenjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device, cuslide::jpeg2k::ColorSpace::kSYCC); break; case cuslide::jpeg2k::kAperioJpeg2kRGB: // 33005 cuslide::jpeg2k::decode_libopenjpeg(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device, cuslide::jpeg2k::ColorSpace::kRGB); break; case COMPRESSION_LZW: cuslide::lzw::decode_lzw(tiff_file, nullptr, tiledata_offset, tiledata_size, &tile_data, tile_raster_nbytes, out_device); // Apply unpredictor // 1: none, 2: horizontal differencing, 3: floating point predictor // https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf if (predictor == 2) { cuslide::lzw::horAcc8(tile_data, tile_raster_nbytes, nbytes_tw); } break; default: throw std::runtime_error("Unsupported compression method"); } } value = image_cache.create_value(tile_data, tile_raster_nbytes); image_cache.insert(key, value); image_cache.unlock(index_hash); } if (copy_partial) { uint32_t fill_gap_x = nbytes_tile_pixel_size_x - fixed_nbytes_tile_pixel_size_x; // Fill original, then fill white for remaining if (fill_gap_x > 0) { for (uint32_t ty = tile_pixel_offset_sy; ty <= fixed_tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { memcpy(dest_start_ptr + dest_pixel_index, tile_data + nbytes_tile_index, fixed_nbytes_tile_pixel_size_x); memset(dest_start_ptr + dest_pixel_index + fixed_nbytes_tile_pixel_size_x, background_value, fill_gap_x); } } else { for (uint32_t ty = tile_pixel_offset_sy; ty <= fixed_tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { memcpy(dest_start_ptr + dest_pixel_index, tile_data + nbytes_tile_index, fixed_nbytes_tile_pixel_size_x); } } for (uint32_t ty = fixed_tile_pixel_offset_ey + 1; ty <= tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y) { memset(dest_start_ptr + dest_pixel_index, background_value, nbytes_tile_pixel_size_x); } } else { for (uint32_t ty = tile_pixel_offset_sy; ty <= tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { memcpy(dest_start_ptr + dest_pixel_index, tile_data + nbytes_tile_index, nbytes_tile_pixel_size_x); } } } } else { if (out_device.type() == cucim::io::DeviceType::kCPU) { for (uint32_t ty = tile_pixel_offset_sy; ty <= tile_pixel_offset_ey; ++ty, dest_pixel_index += dest_pixel_step_y, nbytes_tile_index += nbytes_tw) { // Set (255,255,255) memset(dest_start_ptr + dest_pixel_index, background_value, nbytes_tile_pixel_size_x); } } else { cudaError_t cuda_status; CUDA_ERROR(cudaMemset2D(dest_start_ptr + dest_pixel_index, dest_pixel_step_y, background_value, nbytes_tile_pixel_size_x, tile_pixel_offset_ey - tile_pixel_offset_sy)); } } }; if (loader && *loader) { loader->enqueue(std::move(decode_func), cucim::loader::TileInfo{ location_index, index, tiledata_offset, tiledata_size }); } else { decode_func(); } dest_pixel_index_x += nbytes_tile_pixel_size_x; } dest_start_ptr += dest_pixel_step_y * dest_pixel_offset_len_y; } return true; } } // namespace cuslide::tiff // Hidden methods for benchmarking. #include <fmt/format.h> #include <langinfo.h> #include <iostream> #include <fstream> namespace cuslide::tiff { void IFD::write_offsets_(const char* file_path) { std::ofstream offsets(fmt::format("{}.offsets", file_path), std::ios::out | std::ios::binary | std::ios::trunc); std::ofstream bytecounts(fmt::format("{}.bytecounts", file_path), std::ios::out | std::ios::binary | std::ios::trunc); offsets.write(reinterpret_cast<char*>(&image_piece_count_), sizeof(image_piece_count_)); bytecounts.write(reinterpret_cast<char*>(&image_piece_count_), sizeof(image_piece_count_)); for (uint32_t i = 0; i < image_piece_count_; i++) { offsets.write(reinterpret_cast<char*>(&image_piece_offsets_[i]), sizeof(image_piece_offsets_[i])); bytecounts.write(reinterpret_cast<char*>(&image_piece_bytecounts_[i]), sizeof(image_piece_bytecounts_[i])); } bytecounts.close(); offsets.close(); } } // namespace cuslide::tiff
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/tiff/types.h
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_TYPES_H #define CUSLIDE_TYPES_H #include <cstdint> #include <cucim/codec/methods.h> namespace cuslide::tiff { using ifd_offset_t = uint64_t; enum class TiffType : uint32_t { Generic = 0, Philips = 1, Aperio = 2, }; enum class AssociatedImageBufferType : uint8_t { IFD = 0, IFD_IMAGE_DESC = 1, FILE_OFFSET = 2, BUFFER_POINTER = 3, OWNED_BUFFER_POINTER = 4, }; struct AssociatedImageBufferDesc { AssociatedImageBufferType type; /// 0: IFD index, 1: IFD index + image description offset&size (base64-encoded text) /// 2: file offset + size, 3: buffer pointer (owned by others) + size /// 4: allocated (owned) buffer pointer (so need to free after use) + size cucim::codec::CompressionMethod compression; union { ifd_offset_t ifd_index; struct { ifd_offset_t desc_ifd_index; uint64_t desc_offset; uint64_t desc_size; }; struct { uint64_t file_offset; uint64_t file_size; }; struct { void* buf_ptr; uint64_t buf_size; }; struct { void* owned_ptr; uint64_t owned_size; }; }; }; } // namespace cuslide::tiff #endif // CUSLIDE_TYPES_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/tiff/tiff.cpp
/* * Copyright (c) 2020-2021, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "tiff.h" #include <fcntl.h> #include <algorithm> #include <string> #include <string_view> #include <fmt/format.h> #include <nlohmann/json.hpp> #include <pugixml.hpp> #include <tiffiop.h> #include <cucim/codec/base64.h> #include <cucim/logger/timer.h> #include <cucim/memory/memory_manager.h> #include <cucim/profiler/nvtx3.h> #include "cuslide/jpeg/libjpeg_turbo.h" #include "cuslide/lzw/lzw.h" #include "ifd.h" static constexpr int DEFAULT_IFD_SIZE = 32; using json = nlohmann::json; namespace cuslide::tiff { // djb2 algorithm from http://www.cse.yorku.ca/~oz/hash.html constexpr uint32_t hash_str(const char* str) { uint32_t hash = 5381; uint32_t c = 0; while ((c = *str++)) hash = ((hash << 5) + hash) + c; // hash * 33 + c return hash; } enum class PhilipsMetadataStage : uint8_t { ROOT = 0, SCANNED_IMAGE, PIXEL_DATA_PRESENTATION, ELEMENT, ARRAY_ELEMENT }; enum class PhilipsMetadataType : uint8_t { IString = 0, IDouble, IUInt16, IUInt32, IUInt64 }; static void parse_string_array(const char* values, json& arr, PhilipsMetadataType type) { std::string_view text(values); std::string_view::size_type pos = 0; while ((pos = text.find('"', pos)) != std::string_view::npos) { auto next_pos = text.find('"', pos + 1); if (next_pos != std::string_view::npos) { if (text[next_pos - 1] != '\\') { switch (type) { case PhilipsMetadataType::IString: arr.emplace_back(std::string(text.substr(pos + 1, next_pos - pos - 1))); break; case PhilipsMetadataType::IDouble: arr.emplace_back(std::stod(std::string(text.substr(pos + 1, next_pos - pos - 1)))); break; case PhilipsMetadataType::IUInt16: case PhilipsMetadataType::IUInt32: case PhilipsMetadataType::IUInt64: arr.emplace_back(std::stoul(std::string(text.substr(pos + 1, next_pos - pos - 1)))); break; } pos = next_pos + 1; } } } } static void parse_philips_tiff_metadata(const pugi::xml_node& node, json& metadata, const char* name, PhilipsMetadataStage stage) { switch (stage) { case PhilipsMetadataStage::ROOT: case PhilipsMetadataStage::SCANNED_IMAGE: case PhilipsMetadataStage::PIXEL_DATA_PRESENTATION: for (pugi::xml_node attr = node.child("Attribute"); attr; attr = attr.next_sibling("Attribute")) { const pugi::xml_attribute& attr_attribute = attr.attribute("Name"); if (attr_attribute) { parse_philips_tiff_metadata(attr, metadata, attr_attribute.value(), PhilipsMetadataStage::ELEMENT); } } break; case PhilipsMetadataStage::ARRAY_ELEMENT: break; case PhilipsMetadataStage::ELEMENT: const pugi::xml_attribute& attr_attribute = node.attribute("PMSVR"); auto p_attr_name = attr_attribute.as_string(); if (p_attr_name != nullptr && *p_attr_name != '\0') { if (name) { switch (hash_str(p_attr_name)) { case hash_str("IString"): metadata.emplace(name, node.text().as_string()); break; case hash_str("IDouble"): metadata.emplace(name, node.text().as_double()); break; case hash_str("IUInt16"): metadata.emplace(name, node.text().as_uint()); break; case hash_str("IUInt32"): metadata.emplace(name, node.text().as_uint()); break; case hash_str("IUint64"): metadata.emplace(name, node.text().as_ullong()); break; case hash_str("IStringArray"): { // Process text such as `"a" "b" "c"` auto item_iter = metadata.emplace(name, json::array()); parse_string_array(node.child_value(), *(item_iter.first), PhilipsMetadataType::IString); break; } case hash_str("IDoubleArray"): { // Process text such as `"0.0" "0.1" "0.2"` auto item_iter = metadata.emplace(name, json::array()); parse_string_array(node.child_value(), *(item_iter.first), PhilipsMetadataType::IDouble); break; } case hash_str("IUInt16Array"): { // Process text such as `"1" "2" "3"` auto item_iter = metadata.emplace(name, json::array()); parse_string_array(node.child_value(), *(item_iter.first), PhilipsMetadataType::IUInt16); break; } case hash_str("IUInt32Array"): { // Process text such as `"1" "2" "3"` auto item_iter = metadata.emplace(name, json::array()); parse_string_array(node.child_value(), *(item_iter.first), PhilipsMetadataType::IUInt32); break; } case hash_str("IUInt64Array"): { // Process text such as `"1" "2" "3"` auto item_iter = metadata.emplace(name, json::array()); parse_string_array(node.child_value(), *(item_iter.first), PhilipsMetadataType::IUInt64); break; } case hash_str("IDataObjectArray"): if (strcmp(name, "PIIM_PIXEL_DATA_REPRESENTATION_SEQUENCE") == 0) { const auto& item_array_iter = metadata.emplace(std::string("PIIM_PIXEL_DATA_REPRESENTATION_SEQUENCE"), json::array()); for (pugi::xml_node data_node = node.child("Array").child("DataObject"); data_node; data_node = data_node.next_sibling("DataObject")) { auto& item_iter = item_array_iter.first->emplace_back(json{}); parse_philips_tiff_metadata( data_node, item_iter, nullptr, PhilipsMetadataStage::PIXEL_DATA_PRESENTATION); } } break; } } } break; } } static std::vector<std::string> split_string(std::string_view s, std::string_view delim, size_t capacity = 0) { size_t pos_start = 0; size_t pos_end = -1; size_t delim_len = delim.length(); std::vector<std::string> result; std::string_view item; if (capacity != 0) { result.reserve(capacity); } while ((pos_end = s.find(delim, pos_start)) != std::string_view::npos) { item = s.substr(pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; result.emplace_back(item); } result.emplace_back(s.substr(pos_start)); return result; } static std::string strip_string(const std::string& str) { static const char* white_spaces = " \r\n\t"; std::string::size_type start_pos = str.find_first_not_of(white_spaces); std::string::size_type end_pos = str.find_last_not_of(white_spaces); if (start_pos != std::string::npos) { return str.substr(start_pos, end_pos - start_pos + 1); } else { return std::string(); } } static void parse_aperio_svs_metadata(std::shared_ptr<IFD>& first_ifd, json& metadata) { (void)metadata; std::string& desc = first_ifd->image_description(); // Assumes that metadata's image description starts with 'Aperio '. // It is handled by 'resolve_vendor_format()' std::vector<std::string> items = split_string(desc, "|"); if (items.size() < 1) { return; } // Store the first item of the image description as 'Header' metadata.emplace("Header", items[0]); for (size_t i = 1; i < items.size(); ++i) { std::vector<std::string> key_value = split_string(items[i], " = "); if (key_value.size() == 2) { metadata.emplace(std::move(strip_string(key_value[0])), std::move(strip_string(key_value[1]))); } } } TIFF::~TIFF() { PROF_SCOPED_RANGE(PROF_EVENT(tiff__tiff)); close(); } TIFF::TIFF(const cucim::filesystem::Path& file_path, int mode) : file_path_(file_path) { PROF_SCOPED_RANGE(PROF_EVENT_P(tiff_tiff, 1)); // Copy file path (Allocated memory would be freed at close() method.) char* file_path_cstr = static_cast<char*>(cucim_malloc(file_path.size() + 1)); memcpy(file_path_cstr, file_path.c_str(), file_path.size()); file_path_cstr[file_path.size()] = '\0'; int fd = ::open(file_path_cstr, mode, 0666); if (fd == -1) { cucim_free(file_path_cstr); throw std::invalid_argument(fmt::format("Cannot open {}!", file_path)); } tiff_client_ = ::TIFFFdOpen(fd, file_path_cstr, "rm"); // Add 'm' to disable memory-mapped file if (tiff_client_ == nullptr) { cucim_free(file_path_cstr); throw std::invalid_argument(fmt::format("Cannot load {}!", file_path)); } file_handle_shared_ = std::make_shared<CuCIMFileHandle>(fd, nullptr, FileHandleType::kPosix, file_path_cstr, this); file_handle_ = file_handle_shared_.get(); // TODO: warning if the file is big endian is_big_endian_ = ::TIFFIsBigEndian(tiff_client_); metadata_ = new json{}; } TIFF::TIFF(const cucim::filesystem::Path& file_path, int mode, uint64_t read_config) : TIFF(file_path, mode) { PROF_SCOPED_RANGE(PROF_EVENT_P(tiff_tiff, 2)); read_config_ = read_config; } std::shared_ptr<TIFF> TIFF::open(const cucim::filesystem::Path& file_path, int mode) { auto tif = std::make_shared<TIFF>(file_path, mode); tif->construct_ifds(); return tif; } std::shared_ptr<TIFF> TIFF::open(const cucim::filesystem::Path& file_path, int mode, uint64_t config) { auto tif = std::make_shared<TIFF>(file_path, mode, config); tif->construct_ifds(); return tif; } void TIFF::close() { if (tiff_client_) { TIFFClose(tiff_client_); tiff_client_ = nullptr; } if (metadata_) { delete reinterpret_cast<json*>(metadata_); metadata_ = nullptr; } } void TIFF::construct_ifds() { PROF_SCOPED_RANGE(PROF_EVENT(tiff_construct_ifds)); ifd_offsets_.clear(); ifd_offsets_.reserve(DEFAULT_IFD_SIZE); ifds_.clear(); ifds_.reserve(DEFAULT_IFD_SIZE); uint16_t ifd_index = 0; do { uint64_t offset = TIFFCurrentDirOffset(tiff_client_); ifd_offsets_.push_back(offset); auto ifd = std::make_shared<cuslide::tiff::IFD>(this, ifd_index, offset); ifds_.emplace_back(std::move(ifd)); ++ifd_index; } while (TIFFReadDirectory(tiff_client_)); // Set index for each level level_to_ifd_idx_.reserve(ifd_index); for (size_t index = 0; index < ifd_index; ++index) { level_to_ifd_idx_.emplace_back(index); } // Resolve format and fix `level_to_ifds_idx_` resolve_vendor_format(); // Sort index by resolution (the largest resolution is index 0) std::sort(level_to_ifd_idx_.begin(), level_to_ifd_idx_.end(), [this](const size_t& a, const size_t& b) { uint32_t width_a = this->ifds_[a]->width(); uint32_t width_b = this->ifds_[b]->width(); if (width_a > width_b) { return true; } else if (width_a < width_b) { return false; } else { uint32_t height_a = this->ifds_[a]->height(); uint32_t height_b = this->ifds_[b]->height(); return height_a > height_b; } }); } void TIFF::resolve_vendor_format() { PROF_SCOPED_RANGE(PROF_EVENT(tiff_resolve_vendor_format)); uint16_t ifd_count = ifds_.size(); if (ifd_count == 0) { return; } json* json_metadata = reinterpret_cast<json*>(metadata_); auto& first_ifd = ifds_[0]; std::string& model = first_ifd->model(); std::string& software = first_ifd->software(); const uint16_t resolution_unit = first_ifd->resolution_unit(); const float x_resolution = first_ifd->x_resolution(); const float y_resolution = first_ifd->y_resolution(); // Detect Aperio SVS format { auto& image_desc = first_ifd->image_description(); std::string_view prefix("Aperio "); auto res = std::mismatch(prefix.begin(), prefix.end(), image_desc.begin()); if (res.first == prefix.end()) { _populate_aperio_svs_metadata(ifd_count, json_metadata, first_ifd); } } // Detect Philips TIFF { std::string_view prefix("Philips"); auto res = std::mismatch(prefix.begin(), prefix.end(), software.begin()); if (res.first == prefix.end()) { _populate_philips_tiff_metadata(ifd_count, json_metadata, first_ifd); } } // Append TIFF metadata if (json_metadata) { json tiff_metadata; tiff_metadata.emplace("model", model); tiff_metadata.emplace("software", software); switch (resolution_unit) { case 2: tiff_metadata.emplace("resolution_unit", "inch"); break; case 3: tiff_metadata.emplace("resolution_unit", "centimeter"); break; default: tiff_metadata.emplace("resolution_unit", ""); break; } tiff_metadata.emplace("x_resolution", x_resolution); tiff_metadata.emplace("y_resolution", y_resolution); (*json_metadata).emplace("tiff", std::move(tiff_metadata)); } } void TIFF::_populate_philips_tiff_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd) { json* json_metadata = reinterpret_cast<json*>(metadata); std::string_view macro_prefix("Macro"); std::string_view label_prefix("Label"); pugi::xml_document doc; const char* image_desc_cstr = first_ifd->image_description().c_str(); pugi::xml_parse_result result = doc.load_string(image_desc_cstr); if (result) { const auto& data_object = doc.child("DataObject"); if (std::string_view(data_object.attribute("ObjectType").as_string("")) != "DPUfsImport") { fmt::print( stderr, "[Warning] Failed to read as Philips TIFF. It looks like Philips TIFF but the image description of the first IFD doesn't have '<DataObject ObjectType=\"DPUfsImport\">' node!\n"); return; } pugi::xpath_query PIM_DP_IMAGE_TYPE( "Attribute[@Name='PIM_DP_SCANNED_IMAGES']/Array/DataObject[Attribute/@Name='PIM_DP_IMAGE_TYPE' and Attribute/text()='WSI']"); pugi::xpath_node_set wsi_nodes = PIM_DP_IMAGE_TYPE.evaluate_node_set(data_object); if (wsi_nodes.size() != 1) { fmt::print( stderr, "[Warning] Failed to read as Philips TIFF. Expected only one 'DPScannedImage' node with PIM_DP_IMAGE_TYPE='WSI'.\n"); return; } pugi::xpath_query DICOM_PIXEL_SPACING( "Attribute[@Name='PIIM_PIXEL_DATA_REPRESENTATION_SEQUENCE']/Array/DataObject/Attribute[@Name='DICOM_PIXEL_SPACING']"); pugi::xpath_node_set pixel_spacing_nodes = DICOM_PIXEL_SPACING.evaluate_node_set(wsi_nodes[0]); std::vector<std::pair<double, double>> pixel_spacings; pixel_spacings.reserve(pixel_spacings.size()); for (const pugi::xpath_node& pixel_spacing : pixel_spacing_nodes) { std::string values = pixel_spacing.node().text().as_string(); // Assume that 'values' has a '"<height spacing in mm>" "<width spacing in mm>"' form. double spacing_x = 0.0; double spacing_y = 0.0; std::string::size_type offset = values.find("\""); if (offset != std::string::npos) { spacing_y = std::atof(&values.c_str()[offset + 1]); offset = values.find(" \"", offset); if (offset != std::string::npos) { spacing_x = std::atof(&values.c_str()[offset + 2]); } } if (spacing_x == 0.0 || spacing_y == 0.0) { fmt::print(stderr, "[Warning] Failed to read DICOM_PIXEL_SPACING: {}\n", values); return; } pixel_spacings.emplace_back(std::pair{ spacing_x, spacing_y }); } double spacing_x_l0 = pixel_spacings[0].first; double spacing_y_l0 = pixel_spacings[0].second; uint32_t width_l0 = first_ifd->width(); uint32_t height_l0 = first_ifd->height(); uint16_t spacing_index = 1; for (int index = 1, level_index = 1; index < ifd_count; ++index, ++level_index) { auto& ifd = ifds_[index]; if (ifd->tile_width() == 0) { // TODO: check macro and label AssociatedImageBufferDesc buf_desc{}; buf_desc.type = AssociatedImageBufferType::IFD; buf_desc.compression = static_cast<cucim::codec::CompressionMethod>(ifd->compression()); buf_desc.ifd_index = index; auto& image_desc = ifd->image_description(); if (std::mismatch(macro_prefix.begin(), macro_prefix.end(), image_desc.begin()).first == macro_prefix.end()) { associated_images_.emplace("macro", buf_desc); } else if (std::mismatch(label_prefix.begin(), label_prefix.end(), image_desc.begin()).first == label_prefix.end()) { associated_images_.emplace("label", buf_desc); } // Remove item at index `ifd_index` from `level_to_ifd_idx_` level_to_ifd_idx_.erase(level_to_ifd_idx_.begin() + level_index); --level_index; continue; } double downsample = std::round((pixel_spacings[spacing_index].first / spacing_x_l0 + pixel_spacings[spacing_index].second / spacing_y_l0) / 2); // Fix width and height of IFD ifd->width_ = width_l0 / downsample; ifd->height_ = height_l0 / downsample; ++spacing_index; } constexpr int associated_image_type_count = 2; pugi::xpath_query ASSOCIATED_IMAGES[associated_image_type_count] = { pugi::xpath_query( "Attribute[@Name='PIM_DP_SCANNED_IMAGES']/Array/DataObject[Attribute/@Name='PIM_DP_IMAGE_TYPE' and Attribute/text()='MACROIMAGE'][1]/Attribute[@Name='PIM_DP_IMAGE_DATA']"), pugi::xpath_query( "Attribute[@Name='PIM_DP_SCANNED_IMAGES']/Array/DataObject[Attribute/@Name='PIM_DP_IMAGE_TYPE' and Attribute/text()='LABELIMAGE'][1]/Attribute[@Name='PIM_DP_IMAGE_DATA']") }; constexpr const char* associated_image_names[associated_image_type_count] = { "macro", "label" }; // Add associated image from XML if available (macro and label images) // : Refer to PIM_DP_IMAGE_TYPE in // https://www.openpathology.philips.com/wp-content/uploads/isyntax/4522%20207%2043941_2020_04_24%20Pathology%20iSyntax%20image%20format.pdf for (int associated_image_type_idx = 0; associated_image_type_idx < associated_image_type_count; ++associated_image_type_idx) { pugi::xpath_node associated_node = ASSOCIATED_IMAGES[associated_image_type_idx].evaluate_node(data_object); const char* associated_image_name = associated_image_names[associated_image_type_idx]; // If the associated image doesn't exist if (associated_images_.find(associated_image_name) == associated_images_.end()) { if (associated_node) { auto node_offset = associated_node.node().offset_debug(); if (node_offset >= 0) { // `image_desc_cstr[node_offset]` would point to the following text: // Attribute Element="0x1004" Group="0x301D" Name="PIM_DP_IMAGE_DATA" PMSVR="IString"> // (base64-encoded JPEG image) // </Attribute> // // 34 is from `Attribute Name="PIM_DP_IMAGE_DATA"` char* data_ptr = const_cast<char*>(image_desc_cstr) + node_offset + 34; uint32_t data_len = 0; while (*data_ptr != '>' && *data_ptr != '\0') { ++data_ptr; } if (*data_ptr != '\0') { ++data_ptr; // start of base64-encoded data char* data_end_ptr = data_ptr; // Seek until it finds '<' for '</Attribute>' while (*data_end_ptr != '<' && *data_end_ptr != '\0') { ++data_end_ptr; } data_len = data_end_ptr - data_ptr; } if (data_len > 0) { AssociatedImageBufferDesc buf_desc{}; buf_desc.type = AssociatedImageBufferType::IFD_IMAGE_DESC; buf_desc.compression = cucim::codec::CompressionMethod::JPEG; buf_desc.desc_ifd_index = 0; buf_desc.desc_offset = data_ptr - image_desc_cstr; buf_desc.desc_size = data_len; associated_images_.emplace(associated_image_name, buf_desc); } } } } } // Set TIFF type tiff_type_ = TiffType::Philips; // Set background color background_value_ = 0xFF; // Get metadata if (json_metadata) { json philips_metadata; parse_philips_tiff_metadata(data_object, philips_metadata, nullptr, PhilipsMetadataStage::ROOT); parse_philips_tiff_metadata( wsi_nodes[0].node(), philips_metadata, nullptr, PhilipsMetadataStage::SCANNED_IMAGE); (*json_metadata).emplace("philips", std::move(philips_metadata)); } } } void TIFF::_populate_aperio_svs_metadata(uint16_t ifd_count, void* metadata, std::shared_ptr<IFD>& first_ifd) { (void)ifd_count; (void)metadata; (void)first_ifd; json* json_metadata = reinterpret_cast<json*>(metadata); (void)json_metadata; int32_t non_tile_image_count = 0; // Append associated images for (int index = 1, level_index = 1; index < ifd_count; ++index, ++level_index) { auto& ifd = ifds_[index]; if (ifd->tile_width() == 0) { ++non_tile_image_count; AssociatedImageBufferDesc buf_desc{}; buf_desc.type = AssociatedImageBufferType::IFD; buf_desc.compression = static_cast<cucim::codec::CompressionMethod>(ifd->compression()); buf_desc.ifd_index = index; uint64_t subfile_type = ifd->subfile_type(); // Assumes that associated image can be identified by checking subfile_type if (index == 1 && subfile_type == 0) { associated_images_.emplace("thumbnail", buf_desc); } else if (subfile_type == 1) { associated_images_.emplace("label", buf_desc); } else if (subfile_type == 9) { associated_images_.emplace("macro", buf_desc); } // Remove item at index `ifd_index` from `level_to_ifd_idx_` level_to_ifd_idx_.erase(level_to_ifd_idx_.begin() + level_index); --level_index; continue; } } // Set TIFF type tiff_type_ = TiffType::Aperio; // Set background color background_value_ = 0xFF; // Get metadata if (json_metadata) { json aperio_metadata; parse_aperio_svs_metadata(first_ifd, aperio_metadata); (*json_metadata).emplace("aperio", std::move(aperio_metadata)); } } bool TIFF::read(const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata) { PROF_SCOPED_RANGE(PROF_EVENT(tiff_read)); if (request->associated_image_name) { // 'out_metadata' is only needed for reading associated image return read_associated_image(metadata, request, out_image_data, out_metadata); } const int32_t ndim = request->size_ndim; const uint64_t location_len = request->location_len; if (request->level >= level_to_ifd_idx_.size()) { throw std::invalid_argument(fmt::format( "Invalid level ({}) in the request! (Should be < {})", request->level, level_to_ifd_idx_.size())); } auto main_ifd = ifds_[level_to_ifd_idx_[0]]; auto ifd = ifds_[level_to_ifd_idx_[request->level]]; auto original_img_width = main_ifd->width(); auto original_img_height = main_ifd->height(); for (int32_t i = 0; i < ndim; ++i) { if (request->size[i] <= 0) { throw std::invalid_argument( fmt::format("Invalid size ({}) in the request! (Should be > 0)", request->size[i])); } } if (request->size[0] > original_img_width) { throw std::invalid_argument( fmt::format("Invalid size (it exceeds the original image width {})", original_img_width)); } if (request->size[1] > original_img_height) { throw std::invalid_argument( fmt::format("Invalid size (it exceeds the original image height {})", original_img_height)); } float downsample_factor = metadata->resolution_info.level_downsamples[request->level]; // Change request based on downsample factor. (normalized value at level-0 -> real location at the requested level) for (int64_t i = ndim * location_len - 1; i >= 0; --i) { request->location[i] /= downsample_factor; } return ifd->read(this, metadata, request, out_image_data); } bool TIFF::read_associated_image(const cucim::io::format::ImageMetadataDesc* metadata, const cucim::io::format::ImageReaderRegionRequestDesc* request, cucim::io::format::ImageDataDesc* out_image_data, cucim::io::format::ImageMetadataDesc* out_metadata_desc) { PROF_SCOPED_RANGE(PROF_EVENT(tiff_read_associated_image)); // TODO: implement (void)metadata; std::string device_name(request->device); if (request->shm_name) { device_name = device_name + fmt::format("[{}]", request->shm_name); // TODO: check performance } cucim::io::Device out_device(device_name); uint8_t* raster = nullptr; size_t raster_size = 0; uint32_t width = 0; uint32_t height = 0; uint32_t samples_per_pixel = 0; // Raw metadata for the associated image const char* raw_data_ptr = nullptr; size_t raw_data_len = 0; // Json metadata for the associated image char* json_data_ptr = nullptr; auto associated_image = associated_images_.find(request->associated_image_name); if (associated_image != associated_images_.end()) { auto& buf_desc = associated_image->second; switch (buf_desc.type) { case AssociatedImageBufferType::IFD: { const auto& image_ifd = ifd(buf_desc.ifd_index); auto& image_description = image_ifd->image_description(); auto image_description_size = image_description.size(); // Assign image description into raw_data_ptr raw_data_ptr = image_description.c_str(); raw_data_len = image_description_size; width = image_ifd->width_; height = image_ifd->height_; samples_per_pixel = image_ifd->samples_per_pixel_; raster_size = width * height * samples_per_pixel; uint16_t compression_method = image_ifd->compression_; if (compression_method != COMPRESSION_JPEG && compression_method != COMPRESSION_LZW) { fmt::print(stderr, "[Error] Unsupported compression method in read_associated_image()! (compression: {})\n", compression_method); return false; } raster = static_cast<uint8_t*>(cucim_malloc(raster_size)); // RGB image // Process multi strips const void* jpegtable_data = image_ifd->jpegtable_.data(); uint32_t jpegtable_count = image_ifd->jpegtable_.size(); int jpeg_color_space = image_ifd->jpeg_color_space_; uint16_t predictor = image_ifd->predictor_; uint8_t* target_ptr = raster; uint32_t piece_count = image_ifd->image_piece_count_; uint16_t rows_per_strip = image_ifd->rows_per_strip_; uint32_t row_nbytes = width * samples_per_pixel; uint32_t strip_nbytes = row_nbytes * rows_per_strip; uint32_t start_row = 0; std::vector<uint64_t>& image_piece_offsets = image_ifd->image_piece_offsets_; std::vector<uint64_t>& image_piece_bytecounts = image_ifd->image_piece_bytecounts_; for (int64_t piece_index = 0; piece_index < piece_count; ++piece_index) { uint64_t offset = image_piece_offsets[piece_index]; uint64_t size = image_piece_bytecounts[piece_index]; // If the piece is the last piece, adjust strip_nbytes if (start_row + rows_per_strip >= height) { strip_nbytes = row_nbytes * (height - start_row); } switch (compression_method) { case COMPRESSION_JPEG: if (!cuslide::jpeg::decode_libjpeg(file_handle_->fd, nullptr /*jpeg_buf*/, offset, size, jpegtable_data, jpegtable_count, &target_ptr, out_device, jpeg_color_space)) { cucim_free(raster); fmt::print(stderr, "[Error] Failed to read region with libjpeg!\n"); return false; } break; case COMPRESSION_LZW: if (!cuslide::lzw::decode_lzw(file_handle_->fd, nullptr /*jpeg_buf*/, offset, size, &target_ptr, strip_nbytes, out_device)) { cucim_free(raster); fmt::print(stderr, "[Error] Failed to read region with lzw decoder!\n"); return false; } break; } target_ptr += strip_nbytes; start_row += rows_per_strip; } // Apply unpredictor // 1: none, 2: horizontal differencing, 3: floating point predictor // https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFF6.pdf if (predictor == 2) { cuslide::lzw::horAcc8(raster, raster_size, row_nbytes); } break; } case AssociatedImageBufferType::IFD_IMAGE_DESC: { const auto& image_ifd = ifd(buf_desc.desc_ifd_index); const char* image_desc_buf = image_ifd->image_description().data(); char* decoded_buf = nullptr; int decoded_size = 0; if (!cucim::codec::base64::decode( image_desc_buf, image_ifd->image_description().size(), &decoded_buf, &decoded_size)) { fmt::print(stderr, "[Error] Failed to decode base64-encoded string from the metadata!\n"); return false; } int image_width = 0; int image_height = 0; if (!cuslide::jpeg::get_dimension(decoded_buf, 0, decoded_size, &image_width, &image_height)) { fmt::print(stderr, "[Error] Failed to read jpeg header for image dimension!\n"); return false; } width = image_width; height = image_height; samples_per_pixel = 3; // NOTE: assumes RGB image raster_size = image_width * image_height * samples_per_pixel; raster = static_cast<uint8_t*>(cucim_malloc(raster_size)); // RGB image if (!cuslide::jpeg::decode_libjpeg(-1, reinterpret_cast<unsigned char*>(decoded_buf), 0 /*offset*/, decoded_size, nullptr /*jpegtable_data*/, 0 /*jpegtable_count*/, &raster, out_device)) { cucim_free(raster); fmt::print(stderr, "[Error] Failed to read image from metadata with libjpeg!\n"); return false; } break; } case AssociatedImageBufferType::FILE_OFFSET: // TODO: implement break; case AssociatedImageBufferType::BUFFER_POINTER: // TODO: implement break; case AssociatedImageBufferType::OWNED_BUFFER_POINTER: // TODO: implement break; } } // Populate image data const uint16_t ndim = 3; int64_t* container_shape = static_cast<int64_t*>(cucim_malloc(sizeof(int64_t) * ndim)); container_shape[0] = height; container_shape[1] = width; container_shape[2] = 3; // TODO: hard-coded for 'C' // Copy the raster memory and free it if needed. cucim::memory::move_raster_from_host((void**)&raster, raster_size, out_device); auto& out_image_container = out_image_data->container; out_image_container.data = raster; out_image_container.device = DLDevice{ static_cast<DLDeviceType>(out_device.type()), out_device.index() }; out_image_container.ndim = ndim; out_image_container.dtype = { kDLUInt, 8, 1 }; out_image_container.shape = container_shape; out_image_container.strides = nullptr; // Tensor is compact and row-majored out_image_container.byte_offset = 0; auto& shm_name = out_device.shm_name(); size_t shm_name_len = shm_name.size(); if (shm_name_len != 0) { out_image_data->shm_name = static_cast<char*>(cucim_malloc(shm_name_len + 1)); memcpy(out_image_data->shm_name, shm_name.c_str(), shm_name_len + 1); } else { out_image_data->shm_name = nullptr; } // Populate metadata if (out_metadata_desc && out_metadata_desc->handle) { cucim::io::format::ImageMetadata& out_metadata = *reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle); auto& resource = out_metadata.get_resource(); std::string_view dims{ "YXC" }; std::pmr::vector<int64_t> shape(&resource); shape.reserve(ndim); shape.insert(shape.end(), &container_shape[0], &container_shape[ndim]); DLDataType dtype{ kDLUInt, 8, 1 }; // TODO: Do not assume channel names as 'RGB' std::pmr::vector<std::string_view> channel_names( { std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource); // We don't know physical pixel size for associated image so fill it with default value 1 std::pmr::vector<float> spacing(&resource); spacing.reserve(ndim); spacing.insert(spacing.end(), ndim, 1.0); std::pmr::vector<std::string_view> spacing_units(&resource); spacing_units.reserve(ndim); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "micrometer" }); spacing_units.emplace_back(std::string_view{ "color" }); std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource); // Direction cosines (size is always 3x3) // clang-format off std::pmr::vector<float> direction({ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}, &resource); // clang-format on // The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D // Slicer)) std::string_view coord_sys{ "LPS" }; // Manually set resolution dimensions to 2 const uint16_t level_ndim = 2; std::pmr::vector<int64_t> level_dimensions(&resource); level_dimensions.reserve(level_ndim * 1); // it has only one size level_dimensions.emplace_back(shape[1]); // width level_dimensions.emplace_back(shape[0]); // height std::pmr::vector<float> level_downsamples(&resource); level_downsamples.reserve(1); level_downsamples.emplace_back(1.0); std::pmr::vector<uint32_t> level_tile_sizes(&resource); level_tile_sizes.reserve(level_ndim * 1); // it has only one size level_tile_sizes.emplace_back(shape[1]); // tile_width level_tile_sizes.emplace_back(shape[0]); // tile_height // Empty associated images const size_t associated_image_count = 0; std::pmr::vector<std::string_view> associated_image_names(&resource); std::string_view raw_data{ raw_data_ptr ? raw_data_ptr : "", raw_data_len }; std::string_view json_data{ json_data_ptr ? json_data_ptr : "" }; out_metadata.ndim(ndim); out_metadata.dims(std::move(dims)); out_metadata.shape(std::move(shape)); out_metadata.dtype(dtype); out_metadata.channel_names(std::move(channel_names)); out_metadata.spacing(std::move(spacing)); out_metadata.spacing_units(std::move(spacing_units)); out_metadata.origin(std::move(origin)); out_metadata.direction(std::move(direction)); out_metadata.coord_sys(std::move(coord_sys)); out_metadata.level_count(1); out_metadata.level_ndim(2); out_metadata.level_dimensions(std::move(level_dimensions)); out_metadata.level_downsamples(std::move(level_downsamples)); out_metadata.level_tile_sizes(std::move(level_tile_sizes)); out_metadata.image_count(associated_image_count); out_metadata.image_names(std::move(associated_image_names)); out_metadata.raw_data(raw_data); out_metadata.json_data(json_data); } return true; } cucim::filesystem::Path TIFF::file_path() const { return file_path_; } std::shared_ptr<CuCIMFileHandle>& TIFF::file_handle() { return file_handle_shared_; } ::TIFF* TIFF::client() const { return tiff_client_; } const std::vector<ifd_offset_t>& TIFF::ifd_offsets() const { return ifd_offsets_; } std::shared_ptr<IFD> TIFF::ifd(size_t index) const { return ifds_.at(index); } std::shared_ptr<IFD> TIFF::level_ifd(size_t level_index) const { return ifds_.at(level_to_ifd_idx_.at(level_index)); } size_t TIFF::ifd_count() const { return ifd_offsets_.size(); } size_t TIFF::level_count() const { return level_to_ifd_idx_.size(); } const std::map<std::string, AssociatedImageBufferDesc>& TIFF::associated_images() const { return associated_images_; } size_t TIFF::associated_image_count() const { return associated_images_.size(); } bool TIFF::is_big_endian() const { return is_big_endian_; } uint64_t TIFF::read_config() const { return read_config_; } bool TIFF::is_in_read_config(uint64_t configs) const { return (read_config_ & configs) == configs; } void TIFF::add_read_config(uint64_t configs) { read_config_ |= configs; } TiffType TIFF::tiff_type() { return tiff_type_; } std::string TIFF::metadata() { json* metadata = reinterpret_cast<json*>(metadata_); if (metadata) { return metadata->dump(); } else { return std::string{}; } } void* TIFF::operator new(std::size_t sz) { return cucim_malloc(sz); } void TIFF::operator delete(void* ptr) { cucim_free(ptr); } } // namespace cuslide::tiff
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/loader/nvjpeg_processor.h
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CUSLIDE_NVJPEG_PROCESSOR_H #define CUSLIDE_NVJPEG_PROCESSOR_H #include <condition_variable> #include <memory> #include <mutex> #include <queue> #include <unordered_map> #include <vector> #include <nvjpeg.h> #include <cucim/filesystem/cufile_driver.h> #include <cucim/filesystem/file_handle.h> #include <cucim/io/device.h> #include <cucim/loader/batch_data_processor.h> #include <cucim/loader/tile_info.h> #include "cuslide/tiff/ifd.h" namespace cuslide::loader { class NvJpegProcessor : public cucim::loader::BatchDataProcessor { public: NvJpegProcessor(CuCIMFileHandle* file_handle, const cuslide::tiff::IFD* ifd, const int64_t* request_location, const int64_t* request_size, uint64_t location_len, uint32_t batch_size, uint32_t maximum_tile_count, const uint8_t* jpegtable_data, uint32_t jpegtable_size); ~NvJpegProcessor(); uint32_t request(std::deque<uint32_t>& batch_item_counts, uint32_t num_remaining_patches) override; uint32_t wait_batch(uint32_t index_in_task, std::deque<uint32_t>& batch_item_counts, uint32_t num_remaining_patches) override; std::shared_ptr<cucim::cache::ImageCacheValue> wait_for_processing(uint32_t index) override; void shutdown() override; uint32_t preferred_loader_prefetch_factor(); private: void update_file_block_info(const int64_t* request_location, const int64_t* request_size, uint64_t location_len); bool stopped_ = false; uint32_t preferred_loader_prefetch_factor_ = 2; CuCIMFileHandle* file_handle_ = nullptr; const cuslide::tiff::IFD* ifd_ = nullptr; std::shared_ptr<cucim::filesystem::CuFileDriver> cufile_; size_t tile_width_ = 0; size_t tile_width_bytes_ = 0; size_t tile_height_ = 0; size_t tile_raster_nbytes_ = 0; size_t file_size_ = 0; size_t file_start_offset_ = 0; size_t file_block_size_ = 0; uint32_t cuda_batch_size_ = 1; nvjpegHandle_t handle_ = nullptr; nvjpegOutputFormat_t output_format_ = NVJPEG_OUTPUT_RGBI; nvjpegJpegState_t state_; nvjpegBackend_t backend_ = NVJPEG_BACKEND_GPU_HYBRID_DEVICE; cudaStream_t stream_ = nullptr; std::condition_variable cuda_batch_cond_; std::unique_ptr<cucim::cache::ImageCache> cuda_image_cache_; uint64_t processed_cuda_batch_count_ = 0; cucim::loader::TileInfo fetch_after_{ -1, -1, 0, 0 }; std::deque<uint32_t> cache_tile_queue_; std::unordered_map<uint32_t, cucim::loader::TileInfo> cache_tile_map_; uint8_t* unaligned_host_ = nullptr; uint8_t* aligned_host_ = nullptr; uint8_t* unaligned_device_ = nullptr; uint8_t* aligned_device_ = nullptr; std::vector<const unsigned char*> raw_cuda_inputs_; std::vector<size_t> raw_cuda_inputs_len_; std::vector<nvjpegImage_t> raw_cuda_outputs_; }; } // namespace cuslide::loader #endif // CUSLIDE_NVJPEG_PROCESSOR_H
0
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide
rapidsai_public_repos/cucim/cpp/plugins/cucim.kit.cuslide/src/cuslide/loader/nvjpeg_processor.cpp
/* * Apache License, Version 2.0 * Copyright 2021 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nvjpeg_processor.h" #include <vector> #include <cucim/cache/image_cache_manager.h> #include <cucim/codec/hash_function.h> #include <cucim/io/device.h> #include <cucim/util/cuda.h> #include <fmt/format.h> #define ALIGN_UP(x, align_to) (((uint64_t)(x) + ((uint64_t)(align_to)-1)) & ~((uint64_t)(align_to)-1)) #define ALIGN_DOWN(x, align_to) ((uint64_t)(x) & ~((uint64_t)(align_to)-1)) namespace cuslide::loader { constexpr uint32_t MAX_CUDA_BATCH_SIZE = 1024; NvJpegProcessor::NvJpegProcessor(CuCIMFileHandle* file_handle, const cuslide::tiff::IFD* ifd, const int64_t* request_location, const int64_t* request_size, const uint64_t location_len, const uint32_t batch_size, uint32_t maximum_tile_count, const uint8_t* jpegtable_data, const uint32_t jpegtable_size) : cucim::loader::BatchDataProcessor(batch_size), file_handle_(file_handle), ifd_(ifd) { if (maximum_tile_count > 1) { // Calculate nearlest power of 2 that is equal or larger than the given number. // (Test with https://godbolt.org/z/n7qhPYzfP) int next_candidate = maximum_tile_count & (maximum_tile_count - 1); if (next_candidate > 0) { maximum_tile_count <<= 1; while (true) { next_candidate = maximum_tile_count & (maximum_tile_count - 1); if (next_candidate == 0) { break; } maximum_tile_count = next_candidate; } } // Do not exceed MAX_CUDA_BATCH_SIZE for decoding JPEG with nvJPEG uint32_t cuda_batch_size = std::min(maximum_tile_count, MAX_CUDA_BATCH_SIZE); // Update prefetch_factor // (We can decode/cache tiles at least two times of the number of tiles for batch decoding) // E.g., (128 - 1) / 32 + 1 ~= 4 => 8 (for 256 tiles) for cuda_batch_size(=128) and batch_size(=32) preferred_loader_prefetch_factor_ = ((cuda_batch_size - 1) / batch_size_ + 1) * 2; // Create cuda image cache cucim::cache::ImageCacheConfig cache_config{}; cache_config.type = cucim::cache::CacheType::kPerProcess; cache_config.memory_capacity = 1024 * 1024; // 1TB: set to fairly large memory so that memory_capacity is not a // limiter. cache_config.capacity = cuda_batch_size * 2; // limit the number of cache item to cuda_batch_size * 2 cuda_image_cache_ = std::move(cucim::cache::ImageCacheManager::create_cache(cache_config, cucim::io::DeviceType::kCUDA)); cuda_batch_size_ = cuda_batch_size; // Initialize nvjpeg cudaError_t cuda_status; if (NVJPEG_STATUS_SUCCESS != nvjpegCreate(backend_, NULL, &handle_)) { throw std::runtime_error(fmt::format("NVJPEG initialization error")); } if (NVJPEG_STATUS_SUCCESS != nvjpegJpegStateCreate(handle_, &state_)) { throw std::runtime_error(fmt::format("JPEG state initialization error")); } nvjpegDecodeBatchedParseJpegTables(handle_, state_, jpegtable_data, jpegtable_size); nvjpegDecodeBatchedInitialize(handle_, state_, cuda_batch_size_, 1, output_format_); CUDA_ERROR(cudaStreamCreateWithFlags(&stream_, cudaStreamNonBlocking)); raw_cuda_inputs_.reserve(cuda_batch_size_); raw_cuda_inputs_len_.reserve(cuda_batch_size_); for (uint32_t i = 0; i < cuda_batch_size_; ++i) { raw_cuda_outputs_.emplace_back(); // add all-zero nvjpegImage_t object } // Read file block in advance tile_width_ = ifd->tile_width(); tile_width_bytes_ = tile_width_ * ifd->pixel_size_nbytes(); tile_height_ = ifd->tile_height(); tile_raster_nbytes_ = tile_width_bytes_ * tile_height_; struct stat sb; fstat(file_handle_->fd, &sb); file_size_ = sb.st_size; file_start_offset_ = 0; file_block_size_ = file_size_; update_file_block_info(request_location, request_size, location_len); constexpr int BLOCK_SECTOR_SIZE = 4096; switch (backend_) { case NVJPEG_BACKEND_GPU_HYBRID: cufile_ = cucim::filesystem::open(file_handle->path, "rp"); unaligned_host_ = static_cast<uint8_t*>(cucim_malloc(file_block_size_ + BLOCK_SECTOR_SIZE * 2)); aligned_host_ = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_host_, BLOCK_SECTOR_SIZE)); cufile_->pread(aligned_host_, file_block_size_, file_start_offset_); break; case NVJPEG_BACKEND_GPU_HYBRID_DEVICE: cufile_ = cucim::filesystem::open(file_handle->path, "r"); CUDA_ERROR(cudaMalloc(&unaligned_device_, file_block_size_ + BLOCK_SECTOR_SIZE)); aligned_device_ = reinterpret_cast<uint8_t*>(ALIGN_UP(unaligned_device_, BLOCK_SECTOR_SIZE)); cufile_->pread(aligned_device_, file_block_size_, file_start_offset_); break; default: throw std::runtime_error("Unsupported backend type"); } } } NvJpegProcessor::~NvJpegProcessor() { if (unaligned_host_) { cucim_free(unaligned_host_); unaligned_host_ = nullptr; } cudaError_t cuda_status; if (unaligned_device_) { CUDA_ERROR(cudaFree(unaligned_device_)); unaligned_device_ = nullptr; } for (uint32_t i = 0; i < cuda_batch_size_; ++i) { if (raw_cuda_outputs_[i].channel[0]) { CUDA_ERROR(cudaFree(raw_cuda_outputs_[i].channel[0])); raw_cuda_outputs_[i].channel[0] = nullptr; } } if (state_) { NVJPEG_ERROR(nvjpegJpegStateDestroy(state_)); state_ = nullptr; } if (handle_) { NVJPEG_ERROR(nvjpegDestroy(handle_)); handle_ = nullptr; } } uint32_t NvJpegProcessor::request(std::deque<uint32_t>& batch_item_counts, const uint32_t num_remaining_patches) { (void)batch_item_counts; std::vector<cucim::loader::TileInfo> tile_to_request; if (tiles_.empty()) { return 0; } // Return if we need to wait until previous cuda batch is consumed. auto& first_tile = tiles_.front(); if (first_tile.location_index <= fetch_after_.location_index) { if (first_tile.location_index < fetch_after_.location_index || first_tile.index < fetch_after_.index) { return 0; } } // Set fetch_after_ to the last tile info of previously processed cuda batch if (!cache_tile_queue_.empty()) { fetch_after_ = cache_tile_map_[cache_tile_queue_.back()]; } // Remove previous batch (keep last 'cuda_batch_size_' items) before adding/processing new cuda batch std::vector<cucim::loader::TileInfo> removed_tiles; while (cache_tile_queue_.size() > cuda_batch_size_) { uint32_t removed_tile_index = cache_tile_queue_.front(); auto removed_tile = cache_tile_map_.find(removed_tile_index); removed_tiles.push_back(removed_tile->second); cache_tile_queue_.pop_front(); cache_tile_map_.erase(removed_tile_index); } // Collect candidates for (auto tile : tiles_) { auto index = tile.index; if (tile_to_request.size() >= cuda_batch_size_) { break; } if (cache_tile_map_.find(index) == cache_tile_map_.end()) { if (tile.size == 0) { continue; } cache_tile_queue_.emplace_back(index); cache_tile_map_.emplace(index, tile); tile_to_request.emplace_back(tile); } } // Return if we need to wait until more patches are requested if (tile_to_request.size() < cuda_batch_size_) { if (num_remaining_patches > 0) { // Restore cache_tile_queue_ and cache_tile_map_ for (auto& added_tile : tile_to_request) { uint32_t added_index = added_tile.index; cache_tile_queue_.pop_back(); cache_tile_map_.erase(added_index); } for (auto rit = removed_tiles.rbegin(); rit != removed_tiles.rend(); ++rit) { uint32_t removed_index = rit->index; cache_tile_queue_.emplace_front(removed_index); cache_tile_map_.emplace(removed_index, *rit); } return 0; } else { // Completed, set fetch_after_ to the last tile info. fetch_after_ = tiles_.back(); } } uint8_t* file_block_ptr = nullptr; switch (backend_) { case NVJPEG_BACKEND_GPU_HYBRID: file_block_ptr = aligned_host_; break; case NVJPEG_BACKEND_GPU_HYBRID_DEVICE: file_block_ptr = aligned_device_; break; default: throw std::runtime_error("Unsupported backend type"); } cudaError_t cuda_status; // Initialize batch data with the first data if (raw_cuda_inputs_.empty()) { for (uint32_t i = 0; i < cuda_batch_size_; ++i) { uint8_t* mem_offset = file_block_ptr + tile_to_request[0].offset - file_start_offset_; raw_cuda_inputs_.push_back((const unsigned char*)mem_offset); raw_cuda_inputs_len_.push_back(tile_to_request[0].size); CUDA_ERROR(cudaMallocPitch( &raw_cuda_outputs_[i].channel[0], &raw_cuda_outputs_[i].pitch[0], tile_width_bytes_, tile_height_)); } CUDA_ERROR(cudaStreamSynchronize(stream_)); } // Set inputs to nvJPEG size_t request_count = tile_to_request.size(); for (uint32_t i = 0; i < request_count; ++i) { uint8_t* mem_offset = file_block_ptr + tile_to_request[i].offset - file_start_offset_; raw_cuda_inputs_[i] = mem_offset; raw_cuda_inputs_len_[i] = tile_to_request[i].size; } int error_code = nvjpegDecodeBatched( handle_, state_, raw_cuda_inputs_.data(), raw_cuda_inputs_len_.data(), raw_cuda_outputs_.data(), stream_); if (NVJPEG_STATUS_SUCCESS != error_code) { throw std::runtime_error(fmt::format("Error in batched decode: {}", error_code)); } CUDA_ERROR(cudaStreamSynchronize(stream_)); // Remove previous batch (keep last 'cuda_batch_size_' items) before adding to cuda_image_cache_ // TODO: Utilize the removed tiles if next batch uses them. while (cuda_image_cache_->size() > cuda_batch_size_) { cuda_image_cache_->remove_front(); } // Add to image cache for (uint32_t i = 0; i < request_count; ++i) { auto& added_tile = tile_to_request[i]; uint32_t index = added_tile.index; uint64_t index_hash = cucim::codec::splitmix64(index); auto key = cuda_image_cache_->create_key(0, index); cuda_image_cache_->lock(index_hash); uint8_t* tile_data = static_cast<uint8_t*>(cuda_image_cache_->allocate(tile_raster_nbytes_)); cudaError_t cuda_status; CUDA_TRY(cudaMemcpy2D(tile_data, tile_width_bytes_, raw_cuda_outputs_[i].channel[0], raw_cuda_outputs_[i].pitch[0], tile_width_bytes_, tile_height_, cudaMemcpyDeviceToDevice)); const size_t tile_raster_nbytes = raw_cuda_inputs_len_[i]; auto value = cuda_image_cache_->create_value(tile_data, tile_raster_nbytes, cucim::io::DeviceType::kCUDA); cuda_image_cache_->insert(key, value); cuda_image_cache_->unlock(index_hash); } ++processed_cuda_batch_count_; cuda_batch_cond_.notify_all(); return request_count; } uint32_t NvJpegProcessor::wait_batch(const uint32_t index_in_task, std::deque<uint32_t>& batch_item_counts, const uint32_t num_remaining_patches) { // Check if the next (cuda) batch needs to be requested whenever an index in a task is divided by cuda batch size. // (each task which is for a patch consists of multiple tile processing) if (index_in_task % cuda_batch_size_ == 0) { request(batch_item_counts, num_remaining_patches); } return 0; } std::shared_ptr<cucim::cache::ImageCacheValue> NvJpegProcessor::wait_for_processing(const uint32_t index) { uint64_t index_hash = cucim::codec::splitmix64(index); std::mutex* m = reinterpret_cast<std::mutex*>(cuda_image_cache_->mutex(index_hash)); std::shared_ptr<cucim::cache::ImageCacheValue> value; std::unique_lock<std::mutex> lock(*m); cuda_batch_cond_.wait(lock, [this, index, &value] { // Exit waiting if the thread needs to be stopped or cache value is available. if (stopped_) { value = std::shared_ptr<cucim::cache::ImageCacheValue>(); return true; } auto key = cuda_image_cache_->create_key(0, index); value = cuda_image_cache_->find(key); return static_cast<bool>(value); }); return value; } void NvJpegProcessor::shutdown() { stopped_ = true; cuda_batch_cond_.notify_all(); } uint32_t NvJpegProcessor::preferred_loader_prefetch_factor() { return preferred_loader_prefetch_factor_; } void NvJpegProcessor::update_file_block_info(const int64_t* request_location, const int64_t* request_size, const uint64_t location_len) { uint32_t width = ifd_->width(); uint32_t height = ifd_->height(); uint32_t stride_y = width / tile_width_ + !!(width % tile_width_); // # of tiles in a row(y) in the ifd tile array // as grid uint32_t stride_x = height / tile_height_ + !!(height % tile_height_); // # of tiles in a col(x) in the ifd tile // array as grid int64_t min_tile_index = 1000000000; int64_t max_tile_index = 0; // Assume that offset for tiles are increasing as the index is increasing. for (size_t loc_index = 0; loc_index < location_len; ++loc_index) { int64_t sx = request_location[loc_index * 2]; int64_t sy = request_location[loc_index * 2 + 1]; int64_t offset_sx = static_cast<uint64_t>(sx) / tile_width_; // x-axis start offset for the requested region in // the ifd tile array as grid int64_t offset_sy = static_cast<uint64_t>(sy) / tile_height_; // y-axis start offset for the requested region in // the ifd tile array as grid int64_t tile_index = (offset_sy * stride_y) + offset_sx; min_tile_index = std::min(min_tile_index, tile_index); max_tile_index = std::max(max_tile_index, tile_index); } int64_t w = request_size[0]; int64_t h = request_size[1]; int64_t additional_index_x = (static_cast<uint64_t>(w) + (tile_width_ - 1)) / tile_width_; int64_t additional_index_y = (static_cast<uint64_t>(h) + (tile_height_ - 1)) / tile_height_; min_tile_index = std::max(min_tile_index, 0L); max_tile_index = std::min(stride_x * stride_y - 1, static_cast<uint32_t>(max_tile_index + (additional_index_y * stride_y) + additional_index_x)); auto& image_piece_offsets = const_cast<std::vector<uint64_t>&>(ifd_->image_piece_offsets()); auto& image_piece_bytecounts = const_cast<std::vector<uint64_t>&>(ifd_->image_piece_bytecounts()); uint64_t min_offset = image_piece_offsets[min_tile_index]; uint64_t max_offset = image_piece_offsets[max_tile_index] + image_piece_bytecounts[max_tile_index]; file_start_offset_ = min_offset; file_block_size_ = max_offset - min_offset + 1; } } // namespace cuslide::loader
0
rapidsai_public_repos/cucim/cpp
rapidsai_public_repos/cucim/cpp/cmake/cucim-config.cmake.in
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # @PACKAGE_INIT@ # Find dependent libraries # ... include(CMakeFindDependencyMacro) #find_dependency(Boost x.x.x REQUIRED) find_dependency(CUDAToolkit) if(NOT TARGET cucim::cucim) include(${CMAKE_CURRENT_LIST_DIR}/cucim-targets.cmake) endif()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/modules/CuCIMUtils.cmake
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Store current BUILD_SHARED_LIBS setting in CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_set_build_shared_libs) macro(cucim_set_build_shared_libs new_value) set(CUCIM_OLD_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}}) if (DEFINED CACHE{BUILD_SHARED_LIBS}) set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED TRUE) else() set(CUCIM_OLD_BUILD_SHARED_LIBS_CACHED FALSE) endif() set(BUILD_SHARED_LIBS ${new_value} CACHE BOOL "" FORCE) endmacro() endif() # Restore BUILD_SHARED_LIBS setting from CUCIM_OLD_BUILD_SHARED_LIBS if(NOT COMMAND cucim_restore_build_shared_libs) macro(cucim_restore_build_shared_libs) if (CUCIM_OLD_BUILD_SHARED_LIBS_CACHED) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS} CACHE BOOL "" FORCE) else() unset(BUILD_SHARED_LIBS CACHE) set(BUILD_SHARED_LIBS ${CUCIM_OLD_BUILD_SHARED_LIBS}) endif() endmacro() endif() # Define CMAKE_CUDA_ARCHITECTURES for the given architecture values # # Params: # arch_list - architecture value list (e.g., '60;70;75;80;86') if(NOT COMMAND cucim_define_cuda_architectures) function(cucim_define_cuda_architectures arch_list) set(arch_string "") # Create SASS for all architectures in the list foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${arch}-real") endforeach(arch) # Create PTX for the latest architecture for forward-compatibility. list(GET arch_list -1 latest_arch) foreach(arch IN LISTS arch_list) set(arch_string "${arch_string}" "${latest_arch}-virtual") endforeach(arch) set(CMAKE_CUDA_ARCHITECTURES ${arch_string} PARENT_SCOPE) endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/modules/SuperBuildUtils.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include(FetchContent) set(CMAKE_SUPERBUILD_DEPS_ROOT_DIR "${CMAKE_CURRENT_LIST_DIR}/..") if(NOT COMMAND superbuild_depend) function(superbuild_depend module_name) include("${CMAKE_SUPERBUILD_DEPS_ROOT_DIR}/deps/${module_name}.cmake") endfunction() endif()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/json.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::json) FetchContent_Declare( deps-json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.9.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-json) if (NOT deps-json_POPULATED) message(STATUS "Fetching json sources") FetchContent_Populate(deps-json) message(STATUS "Fetching json sources - done") endif () # Typically you don't care so much for a third party library's tests to be # run from your own project's code. set(JSON_BuildTests OFF CACHE INTERNAL "") add_subdirectory(${deps-json_SOURCE_DIR} ${deps-json_BINARY_DIR} EXCLUDE_FROM_ALL) add_library(deps::json INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::json INTERFACE nlohmann_json::nlohmann_json) set(deps-json_SOURCE_DIR ${deps-json_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-json_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/pybind11_pr4857_4877.patch
diff --git a/CMakeLists.txt b/CMakeLists.txt index 87ec103..f2f1d19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -132,6 +132,7 @@ set(PYBIND11_HEADERS include/pybind11/embed.h include/pybind11/eval.h include/pybind11/gil.h + include/pybind11/gil_safe_call_once.h include/pybind11/iostream.h include/pybind11/functional.h include/pybind11/numpy.h diff --git a/include/pybind11/detail/common.h b/include/pybind11/detail/common.h index 31a54c7..8906c1f 100644 --- a/include/pybind11/detail/common.h +++ b/include/pybind11/detail/common.h @@ -118,6 +118,14 @@ # endif #endif +#if defined(PYBIND11_CPP20) +# define PYBIND11_CONSTINIT constinit +# define PYBIND11_DTOR_CONSTEXPR constexpr +#else +# define PYBIND11_CONSTINIT +# define PYBIND11_DTOR_CONSTEXPR +#endif + // Compiler version assertions #if defined(__INTEL_COMPILER) # if __INTEL_COMPILER < 1800 diff --git a/include/pybind11/gil.h b/include/pybind11/gil.h index 570a558..da22f48 100644 --- a/include/pybind11/gil.h +++ b/include/pybind11/gil.h @@ -11,6 +11,8 @@ #include "detail/common.h" +#include <cassert> + #if defined(WITH_THREAD) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT) # include "detail/internals.h" #endif @@ -137,7 +139,9 @@ private: class gil_scoped_release { public: + // PRECONDITION: The GIL must be held when this constructor is called. explicit gil_scoped_release(bool disassoc = false) : disassoc(disassoc) { + assert(PyGILState_Check()); // `get_internals()` must be called here unconditionally in order to initialize // `internals.tstate` for subsequent `gil_scoped_acquire` calls. Otherwise, an // initialization race could occur as multiple threads try `gil_scoped_acquire`. @@ -201,7 +205,11 @@ class gil_scoped_release { PyThreadState *state; public: - gil_scoped_release() : state{PyEval_SaveThread()} {} + // PRECONDITION: The GIL must be held when this constructor is called. + gil_scoped_release() { + assert(PyGILState_Check()); + state = PyEval_SaveThread(); + } gil_scoped_release(const gil_scoped_release &) = delete; gil_scoped_release &operator=(const gil_scoped_release &) = delete; ~gil_scoped_release() { PyEval_RestoreThread(state); } diff --git a/include/pybind11/gil_safe_call_once.h b/include/pybind11/gil_safe_call_once.h new file mode 100644 index 0000000..58b90b8 --- /dev/null +++ b/include/pybind11/gil_safe_call_once.h @@ -0,0 +1,90 @@ +// Copyright (c) 2023 The pybind Community. + + +#include "detail/common.h" +#include "gil.h" + +#include <cassert> +#include <mutex> + +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) + +// Use the `gil_safe_call_once_and_store` class below instead of the naive +// +// static auto imported_obj = py::module_::import("module_name"); // BAD, DO NOT USE! +// +// which has two serious issues: +// +// 1. Py_DECREF() calls potentially after the Python interpreter was finalized already, and +// 2. deadlocks in multi-threaded processes (because of missing lock ordering). +// +// The following alternative avoids both problems: +// +// PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage; +// auto &imported_obj = storage // Do NOT make this `static`! +// .call_once_and_store_result([]() { +// return py::module_::import("module_name"); +// }) +// .get_stored(); +// +// The parameter of `call_once_and_store_result()` must be callable. It can make +// CPython API calls, and in particular, it can temporarily release the GIL. +// +// `T` can be any C++ type, it does not have to involve CPython API types. +// +// The behavior with regard to signals, e.g. `SIGINT` (`KeyboardInterrupt`), +// is not ideal. If the main thread is the one to actually run the `Callable`, +// then a `KeyboardInterrupt` will interrupt it if it is running normal Python +// code. The situation is different if a non-main thread runs the +// `Callable`, and then the main thread starts waiting for it to complete: +// a `KeyboardInterrupt` will not interrupt the non-main thread, but it will +// get processed only when it is the main thread's turn again and it is running +// normal Python code. However, this will be unnoticeable for quick call-once +// functions, which is usually the case. +template <typename T> +class gil_safe_call_once_and_store { +public: + // PRECONDITION: The GIL must be held when `call_once_and_store_result()` is called. + template <typename Callable> + gil_safe_call_once_and_store &call_once_and_store_result(Callable &&fn) { + if (!is_initialized_) { // This read is guarded by the GIL. + // Multiple threads may enter here, because the GIL is released in the next line and + // CPython API calls in the `fn()` call below may release and reacquire the GIL. + gil_scoped_release gil_rel; // Needed to establish lock ordering. + std::call_once(once_flag_, [&] { + // Only one thread will ever enter here. + gil_scoped_acquire gil_acq; + ::new (storage_) T(fn()); // fn may release, but will reacquire, the GIL. + is_initialized_ = true; // This write is guarded by the GIL. + }); + // All threads will observe `is_initialized_` as true here. + } + // Intentionally not returning `T &` to ensure the calling code is self-documenting. + return *this; + } + + // This must only be called after `call_once_and_store_result()` was called. + T &get_stored() { + assert(is_initialized_); + PYBIND11_WARNING_PUSH +#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5 + // Needed for gcc 4.8.5 + PYBIND11_WARNING_DISABLE_GCC("-Wstrict-aliasing") +#endif + return *reinterpret_cast<T *>(storage_); + PYBIND11_WARNING_POP + } + + constexpr gil_safe_call_once_and_store() = default; + PYBIND11_DTOR_CONSTEXPR ~gil_safe_call_once_and_store() = default; + +private: + alignas(T) char storage_[sizeof(T)] = {}; + std::once_flag once_flag_ = {}; + bool is_initialized_ = false; + // The `is_initialized_`-`storage_` pair is very similar to `std::optional`, + // but the latter does not have the triviality properties of former, + // therefore `std::optional` is not a viable alternative here. +}; + +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) diff --git a/include/pybind11/numpy.h b/include/pybind11/numpy.h index 36077ec..1217c8d 100644 --- a/include/pybind11/numpy.h +++ b/include/pybind11/numpy.h @@ -10,7 +10,10 @@ #pragma once #include "pybind11.h" +#include "detail/common.h" #include "complex.h" +#include "gil_safe_call_once.h" +#include "pytypes.h" #include <algorithm> #include <array> @@ -120,6 +123,20 @@ inline numpy_internals &get_numpy_internals() { return *ptr; } +PYBIND11_NOINLINE module_ import_numpy_core_submodule(const char *submodule_name) { + module_ numpy = module_::import("numpy"); + str version_string = numpy.attr("__version__"); + + module_ numpy_lib = module_::import("numpy.lib"); + object numpy_version = numpy_lib.attr("NumpyVersion")(version_string); + int major_version = numpy_version.attr("major").cast<int>(); + + /* `numpy.core` was renamed to `numpy._core` in NumPy 2.0 as it officially + became a private module. */ + std::string numpy_core_path = major_version >= 2 ? "numpy._core" : "numpy.core"; + return module_::import((numpy_core_path + "." + submodule_name).c_str()); +} + template <typename T> struct same_size { template <typename U> @@ -192,8 +209,8 @@ struct npy_api { }; static npy_api &get() { - static npy_api api = lookup(); - return api; + PYBIND11_CONSTINIT static gil_safe_call_once_and_store<npy_api> storage; + return storage.call_once_and_store_result(lookup).get_stored(); } bool PyArray_Check_(PyObject *obj) const { @@ -263,9 +280,13 @@ private: }; static npy_api lookup() { - module_ m = module_::import("numpy.core.multiarray"); + module_ m = detail::import_numpy_core_submodule("multiarray"); auto c = m.attr("_ARRAY_API"); void **api_ptr = (void **) PyCapsule_GetPointer(c.ptr(), nullptr); + if (api_ptr == nullptr) { + raise_from(PyExc_SystemError, "FAILURE obtaining numpy _ARRAY_API pointer."); + throw error_already_set(); + } npy_api api; #define DECL_NPY_API(Func) api.Func##_ = (decltype(api.Func##_)) api_ptr[API_##Func]; DECL_NPY_API(PyArray_GetNDArrayCFeatureVersion); @@ -625,13 +646,14 @@ public: char flags() const { return detail::array_descriptor_proxy(m_ptr)->flags; } private: - static object _dtype_from_pep3118() { - static PyObject *obj = module_::import("numpy.core._internal") - .attr("_dtype_from_pep3118") - .cast<object>() - .release() - .ptr(); - return reinterpret_borrow<object>(obj); + static object &_dtype_from_pep3118() { + PYBIND11_CONSTINIT static gil_safe_call_once_and_store<object> storage; + return storage + .call_once_and_store_result([]() { + return detail::import_numpy_core_submodule("_internal") + .attr("_dtype_from_pep3118"); + }) + .get_stored(); } dtype strip_padding(ssize_t itemsize) {
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/abseil.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::abseil) FetchContent_Declare( deps-abseil GIT_REPOSITORY https://github.com/abseil/abseil-cpp.git GIT_TAG 20200225.2 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-abseil) if (NOT deps-abseil_POPULATED) message(STATUS "Fetching abseil sources") FetchContent_Populate(deps-abseil) message(STATUS "Fetching abseil sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) set(BUILD_TESTING FALSE) # Disable BUILD_TESTING (cmake-build-debug/_deps/deps-abseil-src/CMakeLists.txt:97) add_subdirectory(${deps-abseil_SOURCE_DIR} ${deps-abseil_BINARY_DIR} EXCLUDE_FROM_ALL) # Set PIC to prevent the following error message # : /usr/bin/ld: ../lib/libabsl_strings.a(escaping.cc.o): relocation R_X86_64_PC32 against symbol `_ZN4absl14lts_2020_02_2516numbers_internal8kHexCharE' can not be used when making a shared object; recompile with -fPIC set_target_properties(absl_strings absl_strings_internal absl_int128 absl_raw_logging_internal PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::abseil INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::abseil INTERFACE absl::strings) set(deps-abseil_SOURCE_DIR ${deps-abseil_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-abseil_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/boost.cmake
# # Copyright (c) 2020-2021, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::boost) set(Boost_VERSION 1.75.0) set(Boost_BUILD_COMPONENTS container) set(Boost_BUILD_OPTIONS "threading=multi cxxflags=-fPIC runtime-link=static variant=release link=static address-model=64 --layout=system") set(Boost_COMPILE_DEFINITIONS BOOST_COROUTINES_NO_DEPRECATION_WARNING=1 BOOST_ALL_NO_LIB=1 BOOST_UUID_RANDOM_PROVIDER_FORCE_WINCRYPT=1 CACHE INTERNAL "Boost compile definitions") set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME ON) foreach(component_name ${Boost_BUILD_COMPONENTS}) list(APPEND Boost_BUILD_VARIANTS --with-${component_name}) endforeach() FetchContent_Declare( deps-boost GIT_REPOSITORY https://github.com/boostorg/boost.git GIT_TAG boost-${Boost_VERSION} GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-boost) if (NOT deps-boost_POPULATED) message(STATUS "Fetching boost sources") FetchContent_Populate(deps-boost) message(STATUS "Fetching boost sources - done") endif () if (deps-boost_POPULATED AND NOT EXISTS "${deps-boost_BINARY_DIR}/install") include(ProcessorCount) ProcessorCount(PROCESSOR_COUNT) execute_process(COMMAND /bin/bash -c "./bootstrap.sh --prefix=${deps-boost_BINARY_DIR}/install && ./b2 install --build-dir=${deps-boost_BINARY_DIR}/build --stagedir=${deps-boost_BINARY_DIR}/stage -j${PROCESSOR_COUNT} ${Boost_BUILD_VARIANTS} ${Boost_BUILD_OPTIONS}" WORKING_DIRECTORY ${deps-boost_SOURCE_DIR} COMMAND_ECHO STDOUT RESULT_VARIABLE Boost_BUILD_RESULT) if(NOT Boost_BUILD_RESULT EQUAL "0") message(FATAL_ERROR "boost library build failed with ${Boost_BUILD_RESULT}, please checkout the boost module configurations") endif() endif() find_package(Boost 1.75 CONFIG REQUIRED COMPONENTS ${Boost_BUILD_COMPONENTS} HINTS ${deps-boost_BINARY_DIR}/install) # /lib/cmake/Boost-${Boost_VERSION} message(STATUS "Boost version: ${Boost_VERSION}") add_library(deps::boost INTERFACE IMPORTED GLOBAL) set_target_properties(deps::boost PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${Boost_INCLUDE_DIRS}" INTERFACE_COMPILE_DEFINITIONS "${Boost_COMPILE_DEFINITIONS}" INTERFACE_LINK_LIBRARIES "${Boost_LIBRARIES}" ) set(deps-boost_SOURCE_DIR ${deps-boost_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-boost_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/boost-header-only.patch
diff --git a/include/boost/interprocess/mem_algo/rbtree_best_fit.hpp b/include/boost/interprocess/mem_algo/rbtree_best_fit.hpp index 7da31f7..5816de7 100644 --- a/include/boost/interprocess/mem_algo/rbtree_best_fit.hpp +++ b/include/boost/interprocess/mem_algo/rbtree_best_fit.hpp @@ -692,7 +692,11 @@ inline T* rbtree_best_fit<MutexFamily, VoidPointer, MemAlignment>:: void* raw_reuse = reuse; void* const ret = priv_allocation_command(command, limit_size, prefer_in_recvd_out_size, raw_reuse, sizeof(T)); reuse = static_cast<T*>(raw_reuse); - BOOST_ASSERT(0 == ((std::size_t)ret % ::boost::container::dtl::alignment_of<T>::value)); + // [cuCIM patch] Ignore assert (ret value is not 64-byte-aligned) so not + // throw assertion failure when used with libcuckoo. This is not well tested. + // + // See https://github.com/boostorg/interprocess/issues/50 + //BOOST_ASSERT(0 == ((std::size_t)ret % ::boost::container::dtl::alignment_of<T>::value)); return static_cast<T*>(ret); }
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/catch2.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::catch2) FetchContent_Declare( deps-catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.4.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-catch2) if (NOT deps-catch2_POPULATED) message(STATUS "Fetching catch2 sources") FetchContent_Populate(deps-catch2) message(STATUS "Fetching catch2 sources - done") endif () add_subdirectory(${deps-catch2_SOURCE_DIR} ${deps-catch2_BINARY_DIR} EXCLUDE_FROM_ALL) # Include Append catch2's cmake module path so that we can use `include(Catch)`. # https://github.com/catchorg/Catch2/blob/devel/docs/cmake-integration.md#catchcmake-and-catchaddtestscmake list(APPEND CMAKE_MODULE_PATH "${deps-catch2_SOURCE_DIR}/extras") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} PARENT_SCOPE) add_library(deps::catch2 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::catch2 INTERFACE Catch2::Catch2) set(deps-catch2_SOURCE_DIR ${deps-catch2_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-catch2_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/rmm.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Note: importing rmm is tricky as it depends on googletest/thrust/spdlog and can conflicts with target names in # the original project. # There is a suggestion in CMake but it seems that it takes time to resolve the issue. # - Namespace support for target names in nested projects: https://gitlab.kitware.com/cmake/cmake/-/issues/16414 if (NOT TARGET deps::rmm) FetchContent_Declare( deps-rmm GIT_REPOSITORY https://github.com/rapidsai/rmm.git GIT_TAG branch-0.17 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-rmm) if (NOT deps-rmm_POPULATED) message(STATUS "Fetching rmm sources") FetchContent_Populate(deps-rmm) message(STATUS "Fetching rmm sources - done") endif () # Create shared library cucim_set_build_shared_libs(ON) # Since rmm doesn't use BUILD_SHARED_LIBS, it always build shared library add_subdirectory(${deps-rmm_SOURCE_DIR} ${deps-rmm_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::rmm INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::rmm INTERFACE rmm) set(deps-rmm_SOURCE_DIR ${deps-rmm_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-rmm_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/googletest.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googletest) FetchContent_Declare( deps-googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.10.0 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googletest) if (NOT deps-googletest_POPULATED) message(STATUS "Fetching googletest sources") FetchContent_Populate(deps-googletest) message(STATUS "Fetching googletest sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-googletest_SOURCE_DIR} ${deps-googletest_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googletest INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googletest INTERFACE googletest) set(deps-googletest_SOURCE_DIR ${deps-googletest_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googletest_SOURCE_DIR) endif () #CMake Warning (dev) in cmake-build-debug/_deps/deps-googletest-src/googlemock/CMakeLists.txt: # Policy CMP0082 is not set: Install rules from add_subdirectory() are # interleaved with those in caller. Run "cmake --help-policy CMP0082" for # policy details. Use the cmake_policy command to set the policy and # suppress this warning.
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/openslide.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::openslide) add_library(deps::openslide SHARED IMPORTED GLOBAL) if (DEFINED ENV{CONDA_BUILD}) set(OPENSLIDE_LIB_PATH "$ENV{PREFIX}/lib/libopenslide.so") elseif (DEFINED ENV{CONDA_PREFIX}) set(OPENSLIDE_LIB_PATH "$ENV{CONDA_PREFIX}/lib/libopenslide.so") elseif (EXISTS /usr/lib/x86_64-linux-gnu/libopenslide.so) set(OPENSLIDE_LIB_PATH /usr/lib/x86_64-linux-gnu/libopenslide.so) elseif (EXISTS /usr/lib/aarch64-linux-gnu/libopenslide.so) set(OPENSLIDE_LIB_PATH /usr/lib/aarch64-linux-gnu/libopenslide.so) else () # CentOS (x86_64) set(OPENSLIDE_LIB_PATH /usr/lib64/libopenslide.so) endif () if (DEFINED ENV{CONDA_BUILD}) set(OPENSLIDE_INCLUDE_PATH "$ENV{PREFIX}/include/") elseif (DEFINED ENV{CONDA_PREFIX}) set(OPENSLIDE_INCLUDE_PATH "$ENV{CONDA_PREFIX}/include/") else () set(OPENSLIDE_INCLUDE_PATH "/usr/include/") endif () set_target_properties(deps::openslide PROPERTIES IMPORTED_LOCATION "${OPENSLIDE_LIB_PATH}" INTERFACE_INCLUDE_DIRECTORIES "${OPENSLIDE_INCLUDE_PATH}" ) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/cli11.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::cli11) FetchContent_Declare( deps-cli11 GIT_REPOSITORY https://github.com/CLIUtils/CLI11.git GIT_TAG v1.9.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-cli11) if (NOT deps-cli11_POPULATED) message(STATUS "Fetching cli11 sources") FetchContent_Populate(deps-cli11) message(STATUS "Fetching cli11 sources - done") endif () add_subdirectory(${deps-cli11_SOURCE_DIR} ${deps-cli11_BINARY_DIR} EXCLUDE_FROM_ALL) add_library(deps::cli11 INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::cli11 INTERFACE CLI11::CLI11) set(deps-cli11_SOURCE_DIR ${deps-cli11_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-cli11_SOURCE_DIR) endif () # Note that library had a failure with nvcc compiler and gcc 9.x headers # ...c++/9/tuple(553): error: pack "_UElements" does not have the same number of elements as "_Elements" # __and_<is_nothrow_assignable<_Elements&, _UElements>...>::value; # Not using nvcc for main code that uses cli11 solved the issue.
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/googlebenchmark.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::googlebenchmark) FetchContent_Declare( deps-googlebenchmark GIT_REPOSITORY https://github.com/google/benchmark.git GIT_TAG v1.5.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-googlebenchmark) if (NOT deps-googlebenchmark_POPULATED) message(STATUS "Fetching googlebenchmark sources") FetchContent_Populate(deps-googlebenchmark) message(STATUS "Fetching googlebenchmark sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) set(BENCHMARK_ENABLE_GTEST_TESTS OFF) add_subdirectory(${deps-googlebenchmark_SOURCE_DIR} ${deps-googlebenchmark_BINARY_DIR} EXCLUDE_FROM_ALL) cucim_restore_build_shared_libs() add_library(deps::googlebenchmark INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::googlebenchmark INTERFACE benchmark::benchmark) set(deps-googlebenchmark_SOURCE_DIR ${deps-googlebenchmark_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-googlebenchmark_SOURCE_DIR) endif ()
0
rapidsai_public_repos/cucim/cpp/cmake
rapidsai_public_repos/cucim/cpp/cmake/deps/fmt.cmake
# # Copyright (c) 2020, NVIDIA CORPORATION. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if (NOT TARGET deps::fmt) FetchContent_Declare( deps-fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 7.0.1 GIT_SHALLOW TRUE ) FetchContent_GetProperties(deps-fmt) if (NOT deps-fmt_POPULATED) message(STATUS "Fetching fmt sources") FetchContent_Populate(deps-fmt) message(STATUS "Fetching fmt sources - done") endif () # Create static library cucim_set_build_shared_libs(OFF) add_subdirectory(${deps-fmt_SOURCE_DIR} ${deps-fmt_BINARY_DIR} EXCLUDE_FROM_ALL) # Set PIC to prevent the following error message # : /usr/bin/ld: ../lib/libfmtd.a(format.cc.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC set_target_properties(fmt PROPERTIES POSITION_INDEPENDENT_CODE ON) cucim_restore_build_shared_libs() add_library(deps::fmt INTERFACE IMPORTED GLOBAL) target_link_libraries(deps::fmt INTERFACE fmt::fmt-header-only) set(deps-fmt_SOURCE_DIR ${deps-fmt_SOURCE_DIR} CACHE INTERNAL "" FORCE) mark_as_advanced(deps-fmt_SOURCE_DIR) endif ()
0