common.cc (2129B)
1 // Copyright (c) the JPEG XL Project Authors. All rights reserved. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 #include "lib/extras/common.h" 7 8 #include <jxl/codestream_header.h> 9 #include <jxl/types.h> 10 11 #include <cstddef> 12 #include <vector> 13 14 #include "lib/extras/packed_image.h" 15 #include "lib/jxl/base/printf_macros.h" 16 #include "lib/jxl/base/status.h" 17 18 namespace jxl { 19 namespace extras { 20 21 Status SelectFormat(const std::vector<JxlPixelFormat>& accepted_formats, 22 const JxlBasicInfo& basic_info, JxlPixelFormat* format) { 23 const size_t original_bit_depth = basic_info.bits_per_sample; 24 size_t current_bit_depth = 0; 25 size_t num_alpha_channels = (basic_info.alpha_bits != 0 ? 1 : 0); 26 size_t num_channels = basic_info.num_color_channels + num_alpha_channels; 27 for (;;) { 28 for (const JxlPixelFormat& candidate : accepted_formats) { 29 if (candidate.num_channels != num_channels) continue; 30 JXL_RETURN_IF_ERROR(PackedImage::ValidateDataType(candidate.data_type)); 31 const size_t candidate_bit_depth = 32 PackedImage::BitsPerChannel(candidate.data_type); 33 if ( 34 // Candidate bit depth is less than what we have and still enough 35 (original_bit_depth <= candidate_bit_depth && 36 candidate_bit_depth < current_bit_depth) || 37 // Or larger than the too-small bit depth we currently have 38 (current_bit_depth < candidate_bit_depth && 39 current_bit_depth < original_bit_depth)) { 40 *format = candidate; 41 current_bit_depth = candidate_bit_depth; 42 } 43 } 44 if (current_bit_depth == 0) { 45 if (num_channels > basic_info.num_color_channels) { 46 // Try dropping the alpha channel. 47 --num_channels; 48 continue; 49 } 50 return JXL_FAILURE("no appropriate format found"); 51 } 52 break; 53 } 54 if (current_bit_depth < original_bit_depth) { 55 JXL_WARNING("encoding %" PRIuS "-bit original to %" PRIuS " bits", 56 original_bit_depth, current_bit_depth); 57 } 58 return true; 59 } 60 61 } // namespace extras 62 } // namespace jxl