2 * Copyright (c) 2024 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <dali/internal/imaging/common/image-operations.h>
21 #include <dali/devel-api/adaptor-framework/image-loading.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/integration-api/trace.h>
24 #include <dali/public-api/common/dali-vector.h>
25 #include <dali/public-api/math/vector2.h>
27 #include <third-party/resampler/resampler.h>
43 // The BORDER_FILL_VALUE is a single byte value that is used for horizontal and vertical borders.
44 // A value of 0x00 gives us transparency for pixel buffers with an alpha channel, or black otherwise.
45 // We can optionally use a Vector4 color here, but at reduced fill speed.
46 const uint8_t BORDER_FILL_VALUE(0x00);
47 // A maximum size limit for newly created bitmaps. ( 1u << 16 ) - 1 is chosen as we are using 16bit words for dimensions.
48 const uint32_t MAXIMUM_TARGET_BITMAP_SIZE((1u << 16) - 1);
50 // Constants used by the ImageResampler.
51 const float DEFAULT_SOURCE_GAMMA = 1.75f; ///< Default source gamma value used in the Resampler() function. Partial gamma correction looks better on mips. Set to 1.0 to disable gamma correction.
52 const float FILTER_SCALE = 1.f; ///< Default filter scale value used in the Resampler() function. Filter scale - values < 1.0 cause aliasing, but create sharper looking mips.
54 const float RAD_135 = Math::PI_2 + Math::PI_4; ///< 135 degrees in radians;
55 const float RAD_225 = RAD_135 + Math::PI_2; ///< 225 degrees in radians;
56 const float RAD_270 = 3.f * Math::PI_2; ///< 270 degrees in radians;
57 const float RAD_315 = RAD_225 + Math::PI_2; ///< 315 degrees in radians;
59 using Integration::Bitmap;
60 using Integration::BitmapPtr;
61 typedef uint8_t PixelBuffer;
63 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_IMAGE_PERFORMANCE_MARKER, false);
66 * @brief 4 byte pixel structure.
74 } __attribute__((packed, aligned(4))); //< Tell the compiler it is okay to use a single 32 bit load.
77 * @brief RGB888 pixel structure.
84 } __attribute__((packed, aligned(1)));
87 * @brief RGB565 pixel typedefed from a short.
89 * Access fields by manual shifting and masking.
91 typedef uint16_t PixelRGB565;
94 * @brief a Pixel composed of two independent byte components.
100 } __attribute__((packed, aligned(2))); //< Tell the compiler it is okay to use a single 16 bit load.
102 #if defined(DEBUG_ENABLED)
104 * Disable logging of image operations or make it verbose from the commandline
105 * as follows (e.g., for dali demo app):
107 * LOG_IMAGE_OPERATIONS=0 dali-demo #< off
108 * LOG_IMAGE_OPERATIONS=3 dali-demo #< on, verbose
111 Debug::Filter* gImageOpsLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_IMAGE_OPERATIONS");
114 /** @return The greatest even number less than or equal to the argument. */
115 inline uint32_t EvenDown(const uint32_t a)
117 const uint32_t evened = a & ~1u;
122 * @brief Log bad parameters.
124 void ValidateScalingParameters(const uint32_t inputWidth,
125 const uint32_t inputHeight,
126 const uint32_t desiredWidth,
127 const uint32_t desiredHeight)
129 if(desiredWidth > inputWidth || desiredHeight > inputHeight)
131 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Upscaling not supported (%u, %u -> %u, %u).\n", inputWidth, inputHeight, desiredWidth, desiredHeight);
134 if(desiredWidth == 0u || desiredHeight == 0u)
136 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Downscaling to a zero-area target is pointless.\n");
139 if(inputWidth == 0u || inputHeight == 0u)
141 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Zero area images cannot be scaled\n");
146 * @brief Do debug assertions common to all scanline halving functions.
147 * @note Inline and in anon namespace so should boil away in release builds.
149 inline void DebugAssertScanlineParameters(const uint8_t* const pixels, const uint32_t width)
151 DALI_ASSERT_DEBUG(pixels && "Null pointer.");
152 DALI_ASSERT_DEBUG(width > 1u && "Can't average fewer than two pixels.");
153 DALI_ASSERT_DEBUG(width < 131072u && "Unusually wide image: are you sure you meant to pass that value in?");
157 * @brief Assertions on params to functions averaging pairs of scanlines.
158 * @note Inline as intended to boil away in release.
160 inline void DebugAssertDualScanlineParameters(const uint8_t* const scanline1,
161 const uint8_t* const scanline2,
162 uint8_t* const outputScanline,
163 const size_t widthInComponents)
165 DALI_ASSERT_DEBUG(scanline1 && "Null pointer.");
166 DALI_ASSERT_DEBUG(scanline2 && "Null pointer.");
167 DALI_ASSERT_DEBUG(outputScanline && "Null pointer.");
168 DALI_ASSERT_DEBUG(((scanline1 >= scanline2 + widthInComponents) || (scanline2 >= scanline1 + widthInComponents)) && "Scanlines alias.");
169 DALI_ASSERT_DEBUG(((outputScanline >= (scanline2 + widthInComponents)) || (scanline2 >= (scanline1 + widthInComponents))) && "Scanline 2 aliases output.");
173 * @brief Converts a scaling mode to the definition of which dimensions matter when box filtering as a part of that mode.
175 BoxDimensionTest DimensionTestForScalingMode(FittingMode::Type fittingMode)
177 BoxDimensionTest dimensionTest;
178 dimensionTest = BoxDimensionTestEither;
182 // Shrink to fit attempts to make one or zero dimensions smaller than the
183 // desired dimensions and one or two dimensions exactly the same as the desired
184 // ones, so as long as one dimension is larger than the desired size, box
185 // filtering can continue even if the second dimension is smaller than the
186 // desired dimensions:
187 case FittingMode::SHRINK_TO_FIT:
189 dimensionTest = BoxDimensionTestEither;
192 // Scale to fill mode keeps both dimensions at least as large as desired:
193 case FittingMode::SCALE_TO_FILL:
195 dimensionTest = BoxDimensionTestBoth;
198 // Y dimension is irrelevant when downscaling in FIT_WIDTH mode:
199 case FittingMode::FIT_WIDTH:
201 dimensionTest = BoxDimensionTestX;
204 // X Dimension is ignored by definition in FIT_HEIGHT mode:
205 case FittingMode::FIT_HEIGHT:
207 dimensionTest = BoxDimensionTestY;
212 return dimensionTest;
216 * @brief Work out the dimensions for a uniform scaling of the input to map it
217 * into the target while effecting ShinkToFit scaling mode.
219 ImageDimensions FitForShrinkToFit(ImageDimensions target, ImageDimensions source)
221 // Scale the input by the least extreme of the two dimensions:
222 const float widthScale = target.GetX() / float(source.GetX());
223 const float heightScale = target.GetY() / float(source.GetY());
224 const float scale = widthScale < heightScale ? widthScale : heightScale;
226 // Do no scaling at all if the result would increase area:
232 return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f);
236 * @brief Work out the dimensions for a uniform scaling of the input to map it
237 * into the target while effecting SCALE_TO_FILL scaling mode.
238 * @note An image scaled into the output dimensions will need either top and
239 * bottom or left and right to be cropped away unless the source was pre-cropped
240 * to match the destination aspect ratio.
242 ImageDimensions FitForScaleToFill(ImageDimensions target, ImageDimensions source)
244 DALI_ASSERT_DEBUG(source.GetX() > 0 && source.GetY() > 0 && "Zero-area rectangles should not be passed-in");
245 // Scale the input by the least extreme of the two dimensions:
246 const float widthScale = target.GetX() / float(source.GetX());
247 const float heightScale = target.GetY() / float(source.GetY());
248 const float scale = widthScale > heightScale ? widthScale : heightScale;
250 // Do no scaling at all if the result would increase area:
256 return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f);
260 * @brief Work out the dimensions for a uniform scaling of the input to map it
261 * into the target while effecting FIT_WIDTH scaling mode.
263 ImageDimensions FitForFitWidth(ImageDimensions target, ImageDimensions source)
265 DALI_ASSERT_DEBUG(source.GetX() > 0 && "Cant fit a zero-dimension rectangle.");
266 const float scale = target.GetX() / float(source.GetX());
268 // Do no scaling at all if the result would increase area:
273 return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f);
277 * @brief Work out the dimensions for a uniform scaling of the input to map it
278 * into the target while effecting FIT_HEIGHT scaling mode.
280 ImageDimensions FitForFitHeight(ImageDimensions target, ImageDimensions source)
282 DALI_ASSERT_DEBUG(source.GetY() > 0 && "Cant fit a zero-dimension rectangle.");
283 const float scale = target.GetY() / float(source.GetY());
285 // Do no scaling at all if the result would increase area:
291 return ImageDimensions(source.GetX() * scale + 0.5f, source.GetY() * scale + 0.5f);
295 * @brief Generate the rectangle to use as the target of a pixel sampling pass
296 * (e.g., nearest or linear).
298 ImageDimensions FitToScalingMode(ImageDimensions requestedSize, ImageDimensions sourceSize, FittingMode::Type fittingMode)
300 ImageDimensions fitDimensions;
303 case FittingMode::SHRINK_TO_FIT:
305 fitDimensions = FitForShrinkToFit(requestedSize, sourceSize);
308 case FittingMode::SCALE_TO_FILL:
310 fitDimensions = FitForScaleToFill(requestedSize, sourceSize);
313 case FittingMode::FIT_WIDTH:
315 fitDimensions = FitForFitWidth(requestedSize, sourceSize);
318 case FittingMode::FIT_HEIGHT:
320 fitDimensions = FitForFitHeight(requestedSize, sourceSize);
325 return fitDimensions;
329 * @brief Calculate the number of lines on the X and Y axis that need to be
330 * either added or removed with repect to the specified fitting mode.
331 * (e.g., nearest or linear).
332 * @param[in] sourceSize The size of the source image
333 * @param[in] fittingMode The fitting mode to use
334 * @param[in/out] requestedSize The target size that the image will be fitted to.
335 * If the source image is smaller than the requested size, the source is not scaled up.
336 * So we reduce the target size while keeping aspect by lowering resolution.
337 * @param[out] scanlinesToCrop The number of scanlines to remove from the image (can be negative to represent Y borders required)
338 * @param[out] columnsToCrop The number of columns to remove from the image (can be negative to represent X borders required)
340 void CalculateBordersFromFittingMode(ImageDimensions sourceSize, FittingMode::Type fittingMode, ImageDimensions& requestedSize, int& scanlinesToCrop, int& columnsToCrop)
342 const int sourceWidth(static_cast<int>(sourceSize.GetWidth()));
343 const int sourceHeight(static_cast<int>(sourceSize.GetHeight()));
344 const float targetAspect(static_cast<float>(requestedSize.GetWidth()) / static_cast<float>(requestedSize.GetHeight()));
350 case FittingMode::FIT_WIDTH:
352 finalWidth = sourceWidth;
353 finalHeight = static_cast<int>(static_cast<float>(sourceWidth) / targetAspect);
357 case FittingMode::FIT_HEIGHT:
359 finalWidth = static_cast<int>(static_cast<float>(sourceHeight) * targetAspect);
360 finalHeight = sourceHeight;
364 case FittingMode::SHRINK_TO_FIT:
366 const float sourceAspect(static_cast<float>(sourceWidth) / static_cast<float>(sourceHeight));
367 if(sourceAspect > targetAspect)
369 finalWidth = sourceWidth;
370 finalHeight = static_cast<int>(static_cast<float>(sourceWidth) / targetAspect);
374 finalWidth = static_cast<int>(static_cast<float>(sourceHeight) * targetAspect);
375 finalHeight = sourceHeight;
380 case FittingMode::SCALE_TO_FILL:
382 const float sourceAspect(static_cast<float>(sourceWidth) / static_cast<float>(sourceHeight));
383 if(sourceAspect > targetAspect)
385 finalWidth = static_cast<int>(static_cast<float>(sourceHeight) * targetAspect);
386 finalHeight = sourceHeight;
390 finalWidth = sourceWidth;
391 finalHeight = static_cast<int>(static_cast<float>(sourceWidth) / targetAspect);
397 // Clamp if overflowed
398 if(DALI_UNLIKELY(finalWidth > std::numeric_limits<uint16_t>::max()))
400 finalWidth = std::numeric_limits<uint16_t>::max();
402 if(DALI_UNLIKELY(finalHeight > std::numeric_limits<uint16_t>::max()))
404 finalHeight = std::numeric_limits<uint16_t>::max();
407 columnsToCrop = -(finalWidth - sourceWidth);
408 scanlinesToCrop = -(finalHeight - sourceHeight);
410 requestedSize.SetWidth(static_cast<uint16_t>(finalWidth));
411 requestedSize.SetHeight(static_cast<uint16_t>(finalHeight));
415 * @brief Construct a pixel buffer object from a copy of the pixel array passed in.
417 Dali::Devel::PixelBuffer MakePixelBuffer(const uint8_t* const pixels, Pixel::Format pixelFormat, uint32_t width, uint32_t height)
419 DALI_ASSERT_DEBUG(pixels && "Null bitmap buffer to copy.");
421 // Allocate a pixel buffer to hold the image passed in:
422 auto newBitmap = Dali::Devel::PixelBuffer::New(width, height, pixelFormat);
424 // Copy over the pixels from the downscaled image that was generated in-place in the pixel buffer of the input bitmap:
425 memcpy(newBitmap.GetBuffer(), pixels, width * height * Pixel::GetBytesPerPixel(pixelFormat));
430 * @brief Work out the desired width and height, accounting for zeros.
432 * @param[in] bitmapWidth Width of image before processing.
433 * @param[in] bitmapHeight Height of image before processing.
434 * @param[in] requestedWidth Width of area to scale image into. Can be zero.
435 * @param[in] requestedHeight Height of area to scale image into. Can be zero.
436 * @return Dimensions of area to scale image into after special rules are applied.
438 ImageDimensions CalculateDesiredDimensions(uint32_t bitmapWidth, uint32_t bitmapHeight, uint32_t requestedWidth, uint32_t requestedHeight)
440 uint32_t maxSize = Dali::GetMaxTextureSize();
442 // If no dimensions have been requested, default to the source ones:
443 if(requestedWidth == 0 && requestedHeight == 0)
445 if(bitmapWidth <= maxSize && bitmapHeight <= maxSize)
447 return ImageDimensions(bitmapWidth, bitmapHeight);
451 // Calculate the size from the max texture size and the source image aspect ratio
452 if(bitmapWidth > bitmapHeight)
454 return ImageDimensions(maxSize, bitmapHeight * maxSize / static_cast<float>(bitmapWidth) + 0.5f);
458 return ImageDimensions(bitmapWidth * maxSize / static_cast<float>(bitmapHeight) + 0.5f, maxSize);
463 // If both dimensions have values requested, use them both:
464 if(requestedWidth != 0 && requestedHeight != 0)
466 if(requestedWidth <= maxSize && requestedHeight <= maxSize)
468 return ImageDimensions(requestedWidth, requestedHeight);
472 // Calculate the size from the max texture size and the source image aspect ratio
473 if(requestedWidth > requestedHeight)
475 return ImageDimensions(maxSize, requestedHeight * maxSize / static_cast<float>(requestedWidth) + 0.5f);
479 return ImageDimensions(requestedWidth * maxSize / static_cast<float>(requestedHeight) + 0.5f, maxSize);
484 // Only one of the dimensions has been requested. Calculate the other from
485 // the requested one and the source image aspect ratio:
486 if(requestedWidth != 0)
488 requestedWidth = std::min(requestedWidth, maxSize);
489 return ImageDimensions(requestedWidth, bitmapHeight / float(bitmapWidth) * requestedWidth + 0.5f);
492 requestedHeight = std::min(requestedHeight, maxSize);
493 return ImageDimensions(bitmapWidth / float(bitmapHeight) * requestedHeight + 0.5f, requestedHeight);
497 * @brief Rotates the given buffer @p pixelsIn 90 degrees counter clockwise.
499 * @note It allocates memory for the returned @p pixelsOut buffer.
500 * @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
501 * @note It may fail if malloc() fails to allocate memory.
503 * @param[in] pixelsIn The input buffer.
504 * @param[in] widthIn The width of the input buffer.
505 * @param[in] heightIn The height of the input buffer.
506 * @param[in] strideIn The stride of the input buffer.
507 * @param[in] pixelSize The size of the pixel.
508 * @param[out] pixelsOut The rotated output buffer.
509 * @param[out] widthOut The width of the output buffer.
510 * @param[out] heightOut The height of the output buffer.
512 * @return Whether the rotation succeeded.
514 bool Rotate90(const uint8_t* const pixelsIn,
523 // The new size of the image.
527 // Allocate memory for the rotated buffer.
528 // Output buffer is tightly packed
529 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
530 if(nullptr == pixelsOut)
532 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
536 // Return if the memory allocations fails.
540 DALI_TRACE_SCOPE(gTraceFilter, "DALI_BITMAP_ROTATE_90");
542 // Rotate the buffer.
543 for(uint32_t y = 0u; y < heightIn; ++y)
545 const uint32_t srcLineIndex = y * strideIn;
546 const uint32_t dstX = y;
547 for(uint32_t x = 0u; x < widthIn; ++x)
549 const uint32_t dstY = heightOut - x - 1u;
550 const uint32_t dstIndex = pixelSize * (dstY * widthOut + dstX);
551 const uint32_t srcIndex = pixelSize * (srcLineIndex + x);
553 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
555 *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel);
564 * @brief Rotates the given buffer @p pixelsIn 180 degrees counter clockwise.
566 * @note It allocates memory for the returned @p pixelsOut buffer.
567 * @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
568 * @note It may fail if malloc() fails to allocate memory.
570 * @param[in] pixelsIn The input buffer.
571 * @param[in] widthIn The width of the input buffer.
572 * @param[in] heightIn The height of the input buffer.
573 * @param[in] strideIn The stride of the input buffer.
574 * @param[in] pixelSize The size of the pixel.
575 * @param[out] pixelsOut The rotated output buffer.
577 * @return Whether the rotation succeeded.
579 bool Rotate180(const uint8_t* const pixelsIn,
586 // Allocate memory for the rotated buffer.
587 // Output buffer is tightly packed
588 pixelsOut = static_cast<uint8_t*>(malloc(widthIn * heightIn * pixelSize));
589 if(nullptr == pixelsOut)
591 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthIn, heightIn, pixelSize);
592 // Return if the memory allocations fails.
596 DALI_TRACE_SCOPE(gTraceFilter, "DALI_BITMAP_ROTATE_180");
598 // Rotate the buffer.
599 for(uint32_t y = 0u; y < heightIn; ++y)
601 const uint32_t srcLineIndex = y * strideIn;
602 const uint32_t dstY = heightIn - y - 1u;
603 for(uint32_t x = 0u; x < widthIn; ++x)
605 const uint32_t dstX = widthIn - x - 1u;
606 const uint32_t dstIndex = pixelSize * (dstY * widthIn + dstX);
607 const uint32_t srcIndex = pixelSize * (srcLineIndex + x);
609 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
611 *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel);
620 * @brief Rotates the given buffer @p pixelsIn 270 degrees counter clockwise.
622 * @note It allocates memory for the returned @p pixelsOut buffer.
623 * @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
624 * @note It may fail if malloc() fails to allocate memory.
626 * @param[in] pixelsIn The input buffer.
627 * @param[in] widthIn The width of the input buffer.
628 * @param[in] heightIn The height of the input buffer.
629 * @param[in] strideIn The stride of the input buffer.
630 * @param[in] pixelSize The size of the pixel.
631 * @param[out] pixelsOut The rotated output buffer.
632 * @param[out] widthOut The width of the output buffer.
633 * @param[out] heightOut The height of the output buffer.
635 * @return Whether the rotation succeeded.
637 bool Rotate270(const uint8_t* const pixelsIn,
646 // The new size of the image.
650 // Allocate memory for the rotated buffer.
651 // Output buffer is tightly packed
652 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
653 if(nullptr == pixelsOut)
655 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
659 // Return if the memory allocations fails.
663 DALI_TRACE_SCOPE(gTraceFilter, "DALI_BITMAP_ROTATE_270");
665 // Rotate the buffer.
666 for(uint32_t y = 0u; y < heightIn; ++y)
668 const uint32_t srcLineIndex = y * strideIn;
669 const uint32_t dstX = widthOut - y - 1u;
670 for(uint32_t x = 0u; x < widthIn; ++x)
672 const uint32_t dstY = x;
673 const uint32_t dstIndex = pixelSize * (dstY * widthOut + dstX);
674 const uint32_t srcIndex = pixelSize * (srcLineIndex + x);
676 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
678 *(pixelsOut + dstIndex + channel) = *(pixelsIn + srcIndex + channel);
687 * @brief Skews a row horizontally (with filtered weights)
689 * @note Limited to 45 degree skewing only.
690 * @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
692 * @param[in] srcBufferPtr Pointer to the input pixel buffer.
693 * @param[in] srcWidth The width of the input pixel buffer.
694 * @param[in] srcStride The stride of the input pixel buffer.
695 * @param[in] pixelSize The size of the pixel.
696 * @param[in,out] dstPixelBuffer Pointer to the output pixel buffer.
697 * @param[in] dstWidth The width of the output pixel buffer.
698 * @param[in] row The row index.
699 * @param[in] offset The skew offset.
700 * @param[in] weight The relative weight of right pixel.
702 void HorizontalSkew(const uint8_t* const srcBufferPtr,
706 uint8_t*& dstBufferPtr,
712 DALI_TRACE_SCOPE(gTraceFilter, "DALI_BITMAP_HORIZONTAL_SKEW");
715 // Fill gap left of skew with background.
716 memset(dstBufferPtr + row * pixelSize * dstWidth, 0u, pixelSize * offset);
719 uint8_t oldLeft[4u] = {0u, 0u, 0u, 0u};
721 for(uint32_t i = 0u; i < srcWidth; ++i)
723 // Loop through row pixels
724 const uint32_t srcIndex = pixelSize * (row * srcStride + i);
726 uint8_t src[4u] = {0u, 0u, 0u, 0u};
727 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
729 src[channel] = *(srcBufferPtr + srcIndex + channel);
733 uint8_t left[4u] = {0u, 0u, 0u, 0u};
734 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
736 left[channel] = static_cast<uint8_t>(static_cast<float>(src[channel]) * weight);
738 // Update left over on source
739 src[channel] -= (left[channel] - oldLeft[channel]);
743 if((static_cast<int32_t>(i) + offset >= 0) && (i + offset < dstWidth))
745 const uint32_t dstIndex = pixelSize * (row * dstWidth + i + offset);
747 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
749 *(dstBufferPtr + dstIndex + channel) = src[channel];
753 // Save leftover for next pixel in scan
754 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
756 oldLeft[channel] = left[channel];
760 // Go to rightmost point of skew
761 int32_t i = std::max(static_cast<int32_t>(srcWidth) + offset, -static_cast<int32_t>(dstWidth * row));
762 if(i < static_cast<int32_t>(dstWidth))
764 // If still in image bounds, put leftovers there
765 const uint32_t dstIndex = pixelSize * (row * dstWidth + i);
767 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
769 *(dstBufferPtr + dstIndex + channel) = oldLeft[channel];
772 // Clear to the right of the skewed line with background
774 memset(dstBufferPtr + pixelSize * (row * dstWidth + i), 0u, pixelSize * (dstWidth - i));
779 * @brief Skews a column vertically (with filtered weights)
781 * @note Limited to 45 degree skewing only.
782 * @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
784 * @param[in] srcBufferPtr Pointer to the input pixel buffer.
785 * @param[in] srcWidth The width of the input pixel buffer.
786 * @param[in] srcHeight The height of the input pixel buffer.
787 * @param[in] srcStride The stride of the input pixel buffer.
788 * @param[in] pixelSize The size of the pixel.
789 * @param[in,out] dstPixelBuffer Pointer to the output pixel buffer.
790 * @param[in] dstWidth The width of the output pixel buffer.
791 * @param[in] dstHeight The height of the output pixel buffer.
792 * @param[in] column The column index.
793 * @param[in] offset The skew offset.
794 * @param[in] weight The relative weight of uppeer pixel.
796 void VerticalSkew(const uint8_t* const srcBufferPtr,
801 uint8_t*& dstBufferPtr,
808 DALI_TRACE_SCOPE(gTraceFilter, "DALI_BITMAP_VERTICAL_SKEW");
809 for(int32_t i = 0; i < offset; ++i)
811 // Fill gap above skew with background
812 const uint32_t dstIndex = pixelSize * (i * dstWidth + column);
814 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
816 *(dstBufferPtr + dstIndex + channel) = 0u;
820 uint8_t oldLeft[4u] = {0u, 0u, 0u, 0u};
824 for(uint32_t i = 0u; i < srcHeight; ++i)
826 // Loop through column pixels
827 const uint32_t srcIndex = pixelSize * (i * srcStride + column);
829 uint8_t src[4u] = {0u, 0u, 0u, 0u};
830 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
832 src[channel] = *(srcBufferPtr + srcIndex + channel);
835 yPos = static_cast<int32_t>(i) + offset;
838 uint8_t left[4u] = {0u, 0u, 0u, 0u};
839 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
841 left[channel] = static_cast<uint8_t>(static_cast<float>(src[channel]) * weight);
842 // Update left over on source
843 src[channel] -= (left[channel] - oldLeft[channel]);
847 if((yPos >= 0) && (yPos < static_cast<int32_t>(dstHeight)))
849 const uint32_t dstIndex = pixelSize * (yPos * dstWidth + column);
851 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
853 *(dstBufferPtr + dstIndex + channel) = src[channel];
857 // Save leftover for next pixel in scan
858 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
860 oldLeft[channel] = left[channel];
864 // Go to bottom point of skew
869 i = static_cast<uint32_t>(yPos);
872 // If still in image bounds, put leftovers there
873 const uint32_t dstIndex = pixelSize * (i * dstWidth + column);
875 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
877 *(dstBufferPtr + dstIndex + channel) = oldLeft[channel];
885 // Clear below skewed line with background
886 const uint32_t dstIndex = pixelSize * (i * dstWidth + column);
888 for(uint32_t channel = 0u; channel < pixelSize; ++channel)
890 *(dstBufferPtr + dstIndex + channel) = 0u;
897 ImageDimensions CalculateDesiredDimensions(ImageDimensions rawDimensions, ImageDimensions requestedDimensions)
899 return CalculateDesiredDimensions(rawDimensions.GetWidth(), rawDimensions.GetHeight(), requestedDimensions.GetWidth(), requestedDimensions.GetHeight());
903 * @brief Apply cropping and padding for specified fitting mode.
905 * Once the bitmap has been (optionally) downscaled to an appropriate size, this method performs alterations
906 * based on the fitting mode.
908 * This will add vertical or horizontal borders if necessary.
909 * Crop the source image data vertically or horizontally if necessary.
910 * The aspect of the source image is preserved.
911 * If the source image is smaller than the desired size, the algorithm will modify the the newly created
912 * bitmaps dimensions to only be as large as necessary, as a memory saving optimization. This will cause
913 * GPU scaling to be performed at render time giving the same result with less texture traversal.
915 * @param[in] bitmap The source pixel buffer to perform modifications on.
916 * @param[in] desiredDimensions The target dimensions to aim to fill based on the fitting mode.
917 * @param[in] fittingMode The fitting mode to use.
919 * @return A new bitmap with the padding and cropping required for fitting mode applied.
920 * If no modification is needed or possible, the passed in bitmap is returned.
922 Dali::Devel::PixelBuffer CropAndPadForFittingMode(Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode);
925 * @brief Adds horizontal or vertical borders to the source image.
927 * @param[in] targetPixels The destination image pointer to draw the borders on.
928 * @param[in] bytesPerPixel The number of bytes per pixel of the target pixel buffer.
929 * @param[in] targetDimensions The dimensions of the destination image.
930 * @param[in] padDimensions The columns and scanlines to pad with borders.
932 void AddBorders(PixelBuffer* targetPixels, const uint32_t bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions);
934 Dali::Devel::PixelBuffer ApplyAttributesToBitmap(Dali::Devel::PixelBuffer bitmap, ImageDimensions dimensions, FittingMode::Type fittingMode, SamplingMode::Type samplingMode)
938 // Calculate the desired box, accounting for a possible zero component:
939 const ImageDimensions desiredDimensions = CalculateDesiredDimensions(bitmap.GetWidth(), bitmap.GetHeight(), dimensions.GetWidth(), dimensions.GetHeight());
941 // If a different size than the raw one has been requested, resize the image
942 // maximally using a repeated box filter without making it smaller than the
943 // requested size in either dimension:
944 bitmap = DownscaleBitmap(bitmap, desiredDimensions, fittingMode, samplingMode);
946 // Cut the bitmap according to the desired width and height so that the
947 // resulting bitmap has the same aspect ratio as the desired dimensions.
948 // Add crop and add borders if necessary depending on fitting mode.
951 bitmap = CropAndPadForFittingMode(bitmap, desiredDimensions, fittingMode);
958 Dali::Devel::PixelBuffer CropAndPadForFittingMode(Dali::Devel::PixelBuffer& bitmap, ImageDimensions desiredDimensions, FittingMode::Type fittingMode)
960 const uint32_t inputWidth = bitmap.GetWidth();
961 const uint32_t inputHeight = bitmap.GetHeight();
962 const uint32_t inputStride = bitmap.GetStride();
964 if(desiredDimensions.GetWidth() < 1u || desiredDimensions.GetHeight() < 1u)
966 DALI_LOG_WARNING("Image scaling aborted as desired dimensions too small (%u, %u).\n", desiredDimensions.GetWidth(), desiredDimensions.GetHeight());
968 else if(inputWidth != desiredDimensions.GetWidth() || inputHeight != desiredDimensions.GetHeight())
970 // Calculate any padding or cropping that needs to be done based on the fitting mode.
971 // Note: If the desired size is larger than the original image, the desired size will be
972 // reduced while maintaining the aspect, in order to save unnecessary memory usage.
973 int scanlinesToCrop = 0;
974 int columnsToCrop = 0;
976 CalculateBordersFromFittingMode(ImageDimensions(inputWidth, inputHeight), fittingMode, desiredDimensions, scanlinesToCrop, columnsToCrop);
978 uint32_t desiredWidth(desiredDimensions.GetWidth());
979 uint32_t desiredHeight(desiredDimensions.GetHeight());
981 // Action the changes by making a new bitmap with the central part of the loaded one if required.
982 if(scanlinesToCrop != 0 || columnsToCrop != 0)
984 // Split the adding and removing of scanlines and columns into separate variables,
985 // so we can use one piece of generic code to action the changes.
986 uint32_t scanlinesToPad = 0;
987 uint32_t columnsToPad = 0;
988 if(scanlinesToCrop < 0)
990 scanlinesToPad = -scanlinesToCrop;
993 if(columnsToCrop < 0)
995 columnsToPad = -columnsToCrop;
999 // If there is no filtering, then the final image size can become very large, exit if larger than maximum.
1000 if((desiredWidth > MAXIMUM_TARGET_BITMAP_SIZE) || (desiredHeight > MAXIMUM_TARGET_BITMAP_SIZE) ||
1001 (columnsToPad > MAXIMUM_TARGET_BITMAP_SIZE) || (scanlinesToPad > MAXIMUM_TARGET_BITMAP_SIZE))
1003 DALI_LOG_WARNING("Image scaling aborted as final dimensions too large (%u, %u).\n", desiredWidth, desiredHeight);
1007 DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_CROP_AND_PAD_BITMAP", [&](std::ostringstream& oss) {
1008 oss << "[origin:" << inputWidth << "x" << inputHeight << " ";
1009 oss << "desired:" << desiredWidth << "x" << desiredHeight << " ";
1010 oss << "fittingMode:" << fittingMode << "]";
1013 // Create new PixelBuffer with the desired size.
1014 const auto pixelFormat = bitmap.GetPixelFormat();
1016 auto croppedBitmap = Devel::PixelBuffer::New(desiredWidth, desiredHeight, pixelFormat);
1018 // Add some pre-calculated offsets to the bitmap pointers so this is not done within a loop.
1019 // The cropping is added to the source pointer, and the padding is added to the destination.
1020 const auto bytesPerPixel = Pixel::GetBytesPerPixel(pixelFormat);
1021 const PixelBuffer* const sourcePixels = bitmap.GetBuffer() + ((((scanlinesToCrop / 2) * inputStride) + (columnsToCrop / 2)) * bytesPerPixel);
1022 PixelBuffer* const targetPixels = croppedBitmap.GetBuffer();
1023 PixelBuffer* const targetPixelsActive = targetPixels + ((((scanlinesToPad / 2) * desiredWidth) + (columnsToPad / 2)) * bytesPerPixel);
1024 DALI_ASSERT_DEBUG(sourcePixels && targetPixels);
1026 // Copy the image data to the new bitmap.
1027 // Optimize to a single memcpy if the left and right edges don't need a crop or a pad.
1028 uint32_t outputSpan(desiredWidth * bytesPerPixel);
1029 if(columnsToCrop == 0 && columnsToPad == 0 && inputStride == inputWidth)
1031 memcpy(targetPixelsActive, sourcePixels, (desiredHeight - scanlinesToPad) * outputSpan);
1035 // The width needs to change (due to either a crop or a pad), so we copy a scanline at a time.
1036 // Precalculate any constants to optimize the inner loop.
1037 const uint32_t inputSpan(inputStride * bytesPerPixel);
1038 const uint32_t copySpan((desiredWidth - columnsToPad) * bytesPerPixel);
1039 const uint32_t scanlinesToCopy(desiredHeight - scanlinesToPad);
1041 for(uint32_t y = 0; y < scanlinesToCopy; ++y)
1043 memcpy(&targetPixelsActive[y * outputSpan], &sourcePixels[y * inputSpan], copySpan);
1047 // Add vertical or horizontal borders to the final image (if required).
1048 desiredDimensions.SetWidth(desiredWidth);
1049 desiredDimensions.SetHeight(desiredHeight);
1050 AddBorders(croppedBitmap.GetBuffer(), bytesPerPixel, desiredDimensions, ImageDimensions(columnsToPad, scanlinesToPad));
1051 // Overwrite the loaded bitmap with the cropped version
1052 bitmap = croppedBitmap;
1054 DALI_TRACE_END(gTraceFilter, "DALI_CROP_AND_PAD_BITMAP");
1061 void AddBorders(PixelBuffer* targetPixels, const uint32_t bytesPerPixel, const ImageDimensions targetDimensions, const ImageDimensions padDimensions)
1063 // Assign ints for faster access.
1064 uint32_t desiredWidth(targetDimensions.GetWidth());
1065 uint32_t desiredHeight(targetDimensions.GetHeight());
1066 uint32_t columnsToPad(padDimensions.GetWidth());
1067 uint32_t scanlinesToPad(padDimensions.GetHeight());
1068 uint32_t outputSpan(desiredWidth * bytesPerPixel);
1070 // Add letterboxing (symmetrical borders) if needed.
1071 if(scanlinesToPad > 0)
1073 // Add a top border. Note: This is (deliberately) rounded down if padding is an odd number.
1074 memset(targetPixels, BORDER_FILL_VALUE, (scanlinesToPad / 2) * outputSpan);
1076 // We subtract scanlinesToPad/2 from scanlinesToPad so that we have the correct
1077 // offset for odd numbers (as the top border is 1 pixel smaller in these cases.
1078 uint32_t bottomBorderHeight = scanlinesToPad - (scanlinesToPad / 2);
1081 memset(&targetPixels[(desiredHeight - bottomBorderHeight) * outputSpan], BORDER_FILL_VALUE, bottomBorderHeight * outputSpan);
1083 else if(columnsToPad > 0)
1085 // Add a left and right border.
1087 // Pre-calculate span size outside of loop.
1088 uint32_t leftBorderSpanWidth((columnsToPad / 2) * bytesPerPixel);
1089 for(uint32_t y = 0; y < desiredHeight; ++y)
1091 memset(&targetPixels[y * outputSpan], BORDER_FILL_VALUE, leftBorderSpanWidth);
1095 // Pre-calculate the initial x offset as it is always the same for a small optimization.
1096 // We subtract columnsToPad/2 from columnsToPad so that we have the correct
1097 // offset for odd numbers (as the left border is 1 pixel smaller in these cases.
1098 uint32_t rightBorderWidth = columnsToPad - (columnsToPad / 2);
1099 PixelBuffer* const destPixelsRightBorder(targetPixels + ((desiredWidth - rightBorderWidth) * bytesPerPixel));
1100 uint32_t rightBorderSpanWidth = rightBorderWidth * bytesPerPixel;
1102 for(uint32_t y = 0; y < desiredHeight; ++y)
1104 memset(&destPixelsRightBorder[y * outputSpan], BORDER_FILL_VALUE, rightBorderSpanWidth);
1109 Dali::Devel::PixelBuffer DownscaleBitmap(Dali::Devel::PixelBuffer bitmap,
1110 ImageDimensions desired,
1111 FittingMode::Type fittingMode,
1112 SamplingMode::Type samplingMode)
1114 // Source dimensions as loaded from resources (e.g. filesystem):
1115 auto bitmapWidth = bitmap.GetWidth();
1116 auto bitmapHeight = bitmap.GetHeight();
1117 auto bitmapStride = bitmap.GetStride();
1118 // Desired dimensions (the rectangle to fit the source image to):
1119 auto desiredWidth = desired.GetWidth();
1120 auto desiredHeight = desired.GetHeight();
1122 Dali::Devel::PixelBuffer outputBitmap{bitmap};
1124 // If a different size than the raw one has been requested, resize the image:
1126 (desiredWidth > 0.0f) && (desiredHeight > 0.0f) &&
1127 ((desiredWidth < bitmapWidth) || (desiredHeight < bitmapHeight)))
1129 DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_DOWNSCALE_BITMAP", [&](std::ostringstream& oss) {
1130 oss << "[origin:" << bitmapWidth << "x" << bitmapHeight << " ";
1131 oss << "desired:" << desiredWidth << "x" << desiredHeight << " ";
1132 oss << "fittingMode:" << fittingMode << " ";
1133 oss << "samplingMode:" << samplingMode << "]";
1135 auto pixelFormat = bitmap.GetPixelFormat();
1137 // Do the fast power of 2 iterated box filter to get to roughly the right side if the filter mode requests that:
1138 uint32_t shrunkWidth = -1, shrunkHeight = -1, outStride = -1;
1139 DownscaleInPlacePow2(bitmap.GetBuffer(), pixelFormat, bitmapWidth, bitmapHeight, bitmapStride, desiredWidth, desiredHeight, fittingMode, samplingMode, shrunkWidth, shrunkHeight, outStride);
1141 // Work out the dimensions of the downscaled bitmap, given the scaling mode and desired dimensions:
1142 const ImageDimensions filteredDimensions = FitToScalingMode(ImageDimensions(desiredWidth, desiredHeight), ImageDimensions(shrunkWidth, shrunkHeight), fittingMode);
1143 const uint32_t filteredWidth = filteredDimensions.GetWidth();
1144 const uint32_t filteredHeight = filteredDimensions.GetHeight();
1146 // Run a filter to scale down the bitmap if it needs it:
1147 bool filtered = false;
1148 if(filteredWidth < shrunkWidth || filteredHeight < shrunkHeight)
1150 if(samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR ||
1151 samplingMode == SamplingMode::NEAREST || samplingMode == SamplingMode::BOX_THEN_NEAREST)
1153 outputBitmap = Dali::Devel::PixelBuffer::New(filteredWidth, filteredHeight, pixelFormat);
1157 if(samplingMode == SamplingMode::LINEAR || samplingMode == SamplingMode::BOX_THEN_LINEAR)
1159 LinearSample(bitmap.GetBuffer(), ImageDimensions(shrunkWidth, shrunkHeight), outStride, pixelFormat, outputBitmap.GetBuffer(), filteredDimensions);
1163 PointSample(bitmap.GetBuffer(), shrunkWidth, shrunkHeight, outStride, pixelFormat, outputBitmap.GetBuffer(), filteredWidth, filteredHeight);
1169 // Copy out the 2^x downscaled, box-filtered pixels if no secondary filter (point or linear) was applied:
1170 if(filtered == false && (shrunkWidth < bitmapWidth || shrunkHeight < bitmapHeight))
1172 // The buffer is downscaled and it is tightly packed. We don't need to set a stride.
1173 outputBitmap = MakePixelBuffer(bitmap.GetBuffer(), pixelFormat, shrunkWidth, shrunkHeight);
1175 DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_DOWNSCALE_BITMAP", [&](std::ostringstream& oss) {
1176 oss << "[origin:" << bitmapWidth << "x" << bitmapHeight << " ";
1177 oss << "desired:" << desiredWidth << "x" << desiredHeight << " ";
1178 oss << "final:" << outputBitmap.GetWidth() << "x" << outputBitmap.GetHeight() << "]";
1182 return outputBitmap;
1188 * @brief Returns whether to keep box filtering based on whether downscaled dimensions will overshoot the desired ones aty the next step.
1189 * @param test Which combination of the two dimensions matter for terminating the filtering.
1190 * @param scaledWidth The width of the current downscaled image.
1191 * @param scaledHeight The height of the current downscaled image.
1192 * @param desiredWidth The target width for the downscaling.
1193 * @param desiredHeight The target height for the downscaling.
1195 bool ContinueScaling(BoxDimensionTest test, uint32_t scaledWidth, uint32_t scaledHeight, uint32_t desiredWidth, uint32_t desiredHeight)
1197 bool keepScaling = false;
1198 const uint32_t nextWidth = scaledWidth >> 1u;
1199 const uint32_t nextHeight = scaledHeight >> 1u;
1201 if(nextWidth >= 1u && nextHeight >= 1u)
1205 case BoxDimensionTestEither:
1207 keepScaling = nextWidth >= desiredWidth || nextHeight >= desiredHeight;
1210 case BoxDimensionTestBoth:
1212 keepScaling = nextWidth >= desiredWidth && nextHeight >= desiredHeight;
1215 case BoxDimensionTestX:
1217 keepScaling = nextWidth >= desiredWidth;
1220 case BoxDimensionTestY:
1222 keepScaling = nextHeight >= desiredHeight;
1232 * @brief A shared implementation of the overall iterative box filter
1233 * downscaling algorithm.
1235 * Specialise this for particular pixel formats by supplying the number of bytes
1236 * per pixel and two functions: one for averaging pairs of neighbouring pixels
1237 * on a single scanline, and a second for averaging pixels at corresponding
1238 * positions on different scanlines.
1241 int BYTES_PER_PIXEL,
1242 void (*HalveScanlineInPlace)(uint8_t* const pixels, const uint32_t width),
1243 void (*AverageScanlines)(const uint8_t* const scanline1, const uint8_t* const __restrict__ scanline2, uint8_t* const outputScanline, const uint32_t width)>
1244 void DownscaleInPlacePow2Generic(uint8_t* const pixels,
1245 const uint32_t inputWidth,
1246 const uint32_t inputHeight,
1247 const uint32_t inputStride,
1248 const uint32_t desiredWidth,
1249 const uint32_t desiredHeight,
1250 BoxDimensionTest dimensionTest,
1252 uint32_t& outHeight,
1253 uint32_t& outStride)
1259 ValidateScalingParameters(inputWidth, inputHeight, desiredWidth, desiredHeight);
1261 // Scale the image until it would be smaller than desired, stopping if the
1262 // resulting height or width would be less than 1:
1263 uint32_t scaledWidth = inputWidth, scaledHeight = inputHeight, stride = inputStride;
1264 while(ContinueScaling(dimensionTest, scaledWidth, scaledHeight, desiredWidth, desiredHeight))
1266 const uint32_t lastWidth = scaledWidth;
1267 const uint32_t lastStride = stride;
1269 scaledHeight >>= 1u;
1270 stride = scaledWidth;
1272 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Scaling to %u\t%u.\n", scaledWidth, scaledHeight);
1274 const uint32_t lastScanlinePair = scaledHeight - 1;
1276 // Scale pairs of scanlines until any spare one at the end is dropped:
1277 for(uint32_t y = 0; y <= lastScanlinePair; ++y)
1279 // Scale two scanlines horizontally:
1280 HalveScanlineInPlace(&pixels[y * 2 * lastStride * BYTES_PER_PIXEL], lastWidth);
1281 HalveScanlineInPlace(&pixels[(y * 2 + 1) * lastStride * BYTES_PER_PIXEL], lastWidth);
1283 // Scale vertical pairs of pixels while the last two scanlines are still warm in
1284 // the CPU cache(s):
1285 // Note, better access patterns for cache-coherence are possible for very large
1286 // images but even a 4k wide RGB888 image will use just 24kB of cache (4k pixels
1287 // * 3 Bpp * 2 scanlines) for two scanlines on the first iteration.
1289 &pixels[y * 2 * lastStride * BYTES_PER_PIXEL],
1290 &pixels[(y * 2 + 1) * lastStride * BYTES_PER_PIXEL],
1291 &pixels[y * scaledWidth * BYTES_PER_PIXEL],
1296 ///@note: we could finish off with one of two mutually exclusive passes, one squashing horizontally as far as possible, and the other vertically, if we knew a following cpu point or bilinear filter would restore the desired aspect ratio.
1297 outWidth = scaledWidth;
1298 outHeight = scaledHeight;
1304 void HalveScanlineInPlaceRGB888(uint8_t* const pixels, const uint32_t width)
1306 DebugAssertScanlineParameters(pixels, width);
1308 const uint32_t lastPair = EvenDown(width - 2);
1312 * for(uint32_t pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel)
1314 * // Load all the byte pixel components we need:
1315 * const uint32_t c11 = pixels[pixel * 3];
1316 * const uint32_t c12 = pixels[pixel * 3 + 1];
1317 * const uint32_t c13 = pixels[pixel * 3 + 2];
1318 * const uint32_t c21 = pixels[pixel * 3 + 3];
1319 * const uint32_t c22 = pixels[pixel * 3 + 4];
1320 * const uint32_t c23 = pixels[pixel * 3 + 5];
1322 * // Save the averaged byte pixel components:
1323 * pixels[outPixel * 3] = static_cast<uint8_t>(AverageComponent(c11, c21));
1324 * pixels[outPixel * 3 + 1] = static_cast<uint8_t>(AverageComponent(c12, c22));
1325 * pixels[outPixel * 3 + 2] = static_cast<uint8_t>(AverageComponent(c13, c23));
1329 //@ToDo : Fix here if we found that collect 12 bytes == 3 uint32_t with 4 colors, and calculate in one-operation
1330 std::uint8_t* inPixelPtr = pixels;
1331 std::uint8_t* outPixelPtr = pixels;
1332 for(std::uint32_t scanedPixelCount = 0; scanedPixelCount <= lastPair; scanedPixelCount += 2)
1334 *(outPixelPtr + 0) = ((*(inPixelPtr + 0) ^ *(inPixelPtr + 3)) >> 1) + (*(inPixelPtr + 0) & *(inPixelPtr + 3));
1335 *(outPixelPtr + 1) = ((*(inPixelPtr + 1) ^ *(inPixelPtr + 4)) >> 1) + (*(inPixelPtr + 1) & *(inPixelPtr + 4));
1336 *(outPixelPtr + 2) = ((*(inPixelPtr + 2) ^ *(inPixelPtr + 5)) >> 1) + (*(inPixelPtr + 2) & *(inPixelPtr + 5));
1342 void HalveScanlineInPlaceRGBA8888(uint8_t* const pixels, const uint32_t width)
1344 DebugAssertScanlineParameters(pixels, width);
1345 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms.");
1347 uint32_t* const alignedPixels = reinterpret_cast<uint32_t*>(pixels);
1349 const uint32_t lastPair = EvenDown(width - 2);
1351 for(uint32_t pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel)
1353 const uint32_t averaged = AveragePixelRGBA8888(alignedPixels[pixel], alignedPixels[pixel + 1]);
1354 alignedPixels[outPixel] = averaged;
1358 void HalveScanlineInPlaceRGB565(uint8_t* pixels, uint32_t width)
1360 DebugAssertScanlineParameters(pixels, width);
1361 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(pixels) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms.");
1363 uint16_t* const alignedPixels = reinterpret_cast<uint16_t*>(pixels);
1365 const uint32_t lastPair = EvenDown(width - 2);
1367 for(uint32_t pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel)
1369 const uint16_t averaged = AveragePixelRGB565(alignedPixels[pixel], alignedPixels[pixel + 1]);
1370 alignedPixels[outPixel] = averaged;
1374 void HalveScanlineInPlace2Bytes(uint8_t* const pixels, const uint32_t width)
1376 DebugAssertScanlineParameters(pixels, width);
1378 const uint32_t lastPair = EvenDown(width - 2);
1380 for(uint32_t pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel)
1384 * // Load all the byte pixel components we need:
1385 * const uint32_t c11 = pixels[pixel * 2];
1386 * const uint32_t c12 = pixels[pixel * 2 + 1];
1387 * const uint32_t c21 = pixels[pixel * 2 + 2];
1388 * const uint32_t c22 = pixels[pixel * 2 + 3];
1390 * // Save the averaged byte pixel components:
1391 * pixels[outPixel * 2] = static_cast<uint8_t>(AverageComponent(c11, c21));
1392 * pixels[outPixel * 2 + 1] = static_cast<uint8_t>(AverageComponent(c12, c22));
1395 // Note : We can assume that pixel is even number. So we can use | operation instead of + operation.
1396 pixels[(outPixel << 1)] = ((pixels[(pixel << 1)] ^ pixels[(pixel << 1) | 2]) >> 1) + (pixels[(pixel << 1)] & pixels[(pixel << 1) | 2]);
1397 pixels[(outPixel << 1) | 1] = ((pixels[(pixel << 1) | 1] ^ pixels[(pixel << 1) | 3]) >> 1) + (pixels[(pixel << 1) | 1] & pixels[(pixel << 1) | 3]);
1401 void HalveScanlineInPlace1Byte(uint8_t* const pixels, const uint32_t width)
1403 DebugAssertScanlineParameters(pixels, width);
1405 const uint32_t lastPair = EvenDown(width - 2);
1407 for(uint32_t pixel = 0, outPixel = 0; pixel <= lastPair; pixel += 2, ++outPixel)
1411 * // Load all the byte pixel components we need:
1412 * const uint32_t c1 = pixels[pixel];
1413 * const uint32_t c2 = pixels[pixel + 1];
1415 * // Save the averaged byte pixel component:
1416 * pixels[outPixel] = static_cast<uint8_t>(AverageComponent(c1, c2));
1419 // Note : We can assume that pixel is even number. So we can use | operation instead of + operation.
1420 pixels[outPixel] = ((pixels[pixel] ^ pixels[pixel | 1]) >> 1) + (pixels[pixel] & pixels[pixel | 1]);
1429 * @copydoc AverageScanlines1
1430 * @note This API average eight components in one operation.
1431 * @note Only possible if each scanline pointer's address aligned
1432 * It will give performance benifit.
1434 inline void AverageScanlinesWithMultipleComponents(
1435 const uint8_t* const scanline1,
1436 const uint8_t* const __restrict__ scanline2,
1437 uint8_t* const outputScanline,
1438 const uint32_t totalComponentCount)
1440 uint32_t component = 0;
1441 if(DALI_LIKELY(totalComponentCount >= 16))
1443 // Note reinsterpret_cast from uint8_t to uint64_t (or uint32_t) and read/write only allowed
1444 // If pointer of data is aligned well.
1445 // (to avoid SIGBUS)
1447 // To increase the percentage of optimized works, let we check pre-padding value of each pointer.
1448 auto scanline1Padding = (reinterpret_cast<std::ptrdiff_t>(scanline1) & (sizeof(std::uint64_t) - 1));
1449 auto scanline2Padding = (reinterpret_cast<std::ptrdiff_t>(scanline2) & (sizeof(std::uint64_t) - 1));
1450 auto outScanlinePadding = (reinterpret_cast<std::ptrdiff_t>(outputScanline) & (sizeof(std::uint64_t) - 1));
1451 if((scanline1Padding == scanline2Padding) && (scanline1Padding == outScanlinePadding))
1453 const auto padding = (sizeof(std::uint64_t) - scanline1Padding) & (sizeof(std::uint64_t) - 1);
1455 // Prepadding range calculate
1456 for(std::uint32_t i = 0; i < padding; ++i)
1458 const auto& c1 = scanline1[i];
1459 const auto& c2 = scanline2[i];
1460 outputScanline[i] = static_cast<std::uint8_t>(((c1 ^ c2) >> 1) + (c1 & c2));
1463 // Jump 8 components in one step
1464 const std::uint64_t* const scanline18Step = reinterpret_cast<const std::uint64_t* const>(scanline1 + padding);
1465 const std::uint64_t* const scanline28Step = reinterpret_cast<const std::uint64_t* const>(scanline2 + padding);
1466 std::uint64_t* const output8step = reinterpret_cast<std::uint64_t* const>(outputScanline + padding);
1468 const std::uint32_t totalStepCount = (totalComponentCount) >> 3;
1469 component = (totalStepCount << 3) + padding;
1471 // and for each step, calculate average of 8 bytes.
1472 for(std::uint32_t i = 0; i < totalStepCount; ++i)
1474 const auto& c1 = *(scanline18Step + i);
1475 const auto& c2 = *(scanline28Step + i);
1476 *(output8step + i) = static_cast<std::uint64_t>((((c1 ^ c2) & 0xfefefefefefefefeull) >> 1) + (c1 & c2));
1479 else if(((scanline1Padding & (sizeof(std::uint32_t) - 1)) == (scanline2Padding & (sizeof(std::uint32_t) - 1))) &&
1480 ((scanline1Padding & (sizeof(std::uint32_t) - 1)) == (outScanlinePadding & (sizeof(std::uint32_t) - 1))))
1482 const auto padding = (sizeof(std::uint64_t) - scanline1Padding) & (sizeof(std::uint32_t) - 1);
1484 // Prepadding range calculate
1485 for(std::uint32_t i = 0; i < padding; ++i)
1487 const auto& c1 = scanline1[i];
1488 const auto& c2 = scanline2[i];
1489 outputScanline[i] = static_cast<std::uint8_t>(((c1 ^ c2) >> 1) + (c1 & c2));
1492 // Jump 4 components in one step
1493 const std::uint32_t* const scanline14Step = reinterpret_cast<const std::uint32_t* const>(scanline1 + padding);
1494 const std::uint32_t* const scanline24Step = reinterpret_cast<const std::uint32_t* const>(scanline2 + padding);
1495 std::uint32_t* const output4step = reinterpret_cast<std::uint32_t* const>(outputScanline + padding);
1497 const std::uint32_t totalStepCount = (totalComponentCount) >> 2;
1498 component = (totalStepCount << 2) + padding;
1500 // and for each step, calculate average of 4 bytes.
1501 for(std::uint32_t i = 0; i < totalStepCount; ++i)
1503 const auto& c1 = *(scanline14Step + i);
1504 const auto& c2 = *(scanline24Step + i);
1505 *(output4step + i) = static_cast<std::uint32_t>((((c1 ^ c2) & 0xfefefefeu) >> 1) + (c1 & c2));
1509 // remaining components calculate
1510 for(; component < totalComponentCount; ++component)
1512 const auto& c1 = scanline1[component];
1513 const auto& c2 = scanline2[component];
1514 outputScanline[component] = static_cast<std::uint8_t>(((c1 ^ c2) >> 1) + (c1 & c2));
1520 void AverageScanlines1(const uint8_t* const scanline1,
1521 const uint8_t* const __restrict__ scanline2,
1522 uint8_t* const outputScanline,
1523 const uint32_t width)
1525 DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width);
1529 * for(uint32_t component = 0; component < width; ++component)
1531 * outputScanline[component] = static_cast<uint8_t>(AverageComponent(scanline1[component], scanline2[component]));
1535 AverageScanlinesWithMultipleComponents(scanline1, scanline2, outputScanline, width);
1538 void AverageScanlines2(const uint8_t* const scanline1,
1539 const uint8_t* const __restrict__ scanline2,
1540 uint8_t* const outputScanline,
1541 const uint32_t width)
1543 DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 2);
1547 * for(uint32_t component = 0; component < width * 2; ++component)
1549 * outputScanline[component] = static_cast<uint8_t>(AverageComponent(scanline1[component], scanline2[component]));
1553 AverageScanlinesWithMultipleComponents(scanline1, scanline2, outputScanline, width * 2);
1556 void AverageScanlines3(const uint8_t* const scanline1,
1557 const uint8_t* const __restrict__ scanline2,
1558 uint8_t* const outputScanline,
1559 const uint32_t width)
1561 DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 3);
1565 * for(uint32_t component = 0; component < width * 3; ++component)
1567 * outputScanline[component] = static_cast<uint8_t>(AverageComponent(scanline1[component], scanline2[component]));
1571 AverageScanlinesWithMultipleComponents(scanline1, scanline2, outputScanline, width * 3);
1574 void AverageScanlinesRGBA8888(const uint8_t* const scanline1,
1575 const uint8_t* const __restrict__ scanline2,
1576 uint8_t* const outputScanline,
1577 const uint32_t width)
1579 DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 4);
1580 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(scanline1) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms.");
1581 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(scanline2) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms.");
1582 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(outputScanline) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms.");
1586 * const uint32_t* const alignedScanline1 = reinterpret_cast<const uint32_t*>(scanline1);
1587 * const uint32_t* const alignedScanline2 = reinterpret_cast<const uint32_t*>(scanline2);
1588 * uint32_t* const alignedOutput = reinterpret_cast<uint32_t*>(outputScanline);
1590 * for(uint32_t pixel = 0; pixel < width; ++pixel)
1592 * alignedOutput[pixel] = AveragePixelRGBA8888(alignedScanline1[pixel], alignedScanline2[pixel]);
1597 AverageScanlinesWithMultipleComponents(scanline1, scanline2, outputScanline, width * 4u);
1600 void AverageScanlinesRGB565(const uint8_t* const scanline1,
1601 const uint8_t* const __restrict__ scanline2,
1602 uint8_t* const outputScanline,
1603 const uint32_t width)
1605 DebugAssertDualScanlineParameters(scanline1, scanline2, outputScanline, width * 2);
1606 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(scanline1) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms.");
1607 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(scanline2) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms.");
1608 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(outputScanline) & 1u) == 0u) && "Pointer should be 2-byte aligned for performance on some platforms.");
1610 const uint16_t* const alignedScanline1 = reinterpret_cast<const uint16_t*>(scanline1);
1611 const uint16_t* const alignedScanline2 = reinterpret_cast<const uint16_t*>(scanline2);
1612 uint16_t* const alignedOutput = reinterpret_cast<uint16_t*>(outputScanline);
1614 for(uint32_t pixel = 0; pixel < width; ++pixel)
1616 alignedOutput[pixel] = AveragePixelRGB565(alignedScanline1[pixel], alignedScanline2[pixel]);
1620 /// Dispatch to pixel format appropriate box filter downscaling functions.
1621 void DownscaleInPlacePow2(uint8_t* const pixels,
1622 Pixel::Format pixelFormat,
1623 uint32_t inputWidth,
1624 uint32_t inputHeight,
1625 uint32_t inputStride,
1626 uint32_t desiredWidth,
1627 uint32_t desiredHeight,
1628 FittingMode::Type fittingMode,
1629 SamplingMode::Type samplingMode,
1631 uint32_t& outHeight,
1632 uint32_t& outStride)
1634 outWidth = inputWidth;
1635 outHeight = inputHeight;
1636 outStride = inputStride;
1637 // Perform power of 2 iterated 4:1 box filtering if the requested filter mode requires it:
1638 if(samplingMode == SamplingMode::BOX || samplingMode == SamplingMode::BOX_THEN_NEAREST || samplingMode == SamplingMode::BOX_THEN_LINEAR)
1640 // Check the pixel format is one that is supported:
1641 if(pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::CHROMINANCE_U || pixelFormat == Pixel::CHROMINANCE_V)
1643 const BoxDimensionTest dimensionTest = DimensionTestForScalingMode(fittingMode);
1647 case Pixel::RGBA8888:
1649 Internal::Platform::DownscaleInPlacePow2RGBA8888(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1654 Internal::Platform::DownscaleInPlacePow2RGB888(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1659 Internal::Platform::DownscaleInPlacePow2RGB565(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1664 Internal::Platform::DownscaleInPlacePow2ComponentPair(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1669 case Pixel::CHROMINANCE_U:
1670 case Pixel::CHROMINANCE_V:
1672 Internal::Platform::DownscaleInPlacePow2SingleBytePerPixel(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1677 DALI_ASSERT_DEBUG(false && "Inner branch conditions don't match outer branch.");
1684 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not shrunk: unsupported pixel format: %u.\n", uint32_t(pixelFormat));
1688 void DownscaleInPlacePow2RGB888(uint8_t* pixels,
1689 uint32_t inputWidth,
1690 uint32_t inputHeight,
1691 uint32_t inputStride,
1692 uint32_t desiredWidth,
1693 uint32_t desiredHeight,
1694 BoxDimensionTest dimensionTest,
1696 uint32_t& outHeight,
1697 uint32_t& outStride)
1699 DownscaleInPlacePow2Generic<3, HalveScanlineInPlaceRGB888, AverageScanlines3>(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1702 void DownscaleInPlacePow2RGBA8888(uint8_t* pixels,
1703 uint32_t inputWidth,
1704 uint32_t inputHeight,
1705 uint32_t inputStride,
1706 uint32_t desiredWidth,
1707 uint32_t desiredHeight,
1708 BoxDimensionTest dimensionTest,
1710 uint32_t& outHeight,
1711 uint32_t& outStride)
1713 DALI_ASSERT_DEBUG(((reinterpret_cast<ptrdiff_t>(pixels) & 3u) == 0u) && "Pointer should be 4-byte aligned for performance on some platforms.");
1714 DownscaleInPlacePow2Generic<4, HalveScanlineInPlaceRGBA8888, AverageScanlinesRGBA8888>(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1717 void DownscaleInPlacePow2RGB565(uint8_t* pixels,
1718 uint32_t inputWidth,
1719 uint32_t inputHeight,
1720 uint32_t inputStride,
1721 uint32_t desiredWidth,
1722 uint32_t desiredHeight,
1723 BoxDimensionTest dimensionTest,
1725 uint32_t& outHeight,
1726 uint32_t& outStride)
1728 DownscaleInPlacePow2Generic<2, HalveScanlineInPlaceRGB565, AverageScanlinesRGB565>(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1732 * @copydoc DownscaleInPlacePow2RGB888
1734 * For 2-byte formats such as lum8alpha8, but not packed 16 bit formats like RGB565.
1736 void DownscaleInPlacePow2ComponentPair(uint8_t* pixels,
1737 uint32_t inputWidth,
1738 uint32_t inputHeight,
1739 uint32_t inputStride,
1740 uint32_t desiredWidth,
1741 uint32_t desiredHeight,
1742 BoxDimensionTest dimensionTest,
1744 uint32_t& outHeight,
1745 uint32_t& outStride)
1747 DownscaleInPlacePow2Generic<2, HalveScanlineInPlace2Bytes, AverageScanlines2>(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1750 void DownscaleInPlacePow2SingleBytePerPixel(uint8_t* pixels,
1751 uint32_t inputWidth,
1752 uint32_t inputHeight,
1753 uint32_t inputStride,
1754 uint32_t desiredWidth,
1755 uint32_t desiredHeight,
1756 BoxDimensionTest dimensionTest,
1758 uint32_t& outHeight,
1759 uint32_t& outStride)
1761 DownscaleInPlacePow2Generic<1, HalveScanlineInPlace1Byte, AverageScanlines1>(pixels, inputWidth, inputHeight, inputStride, desiredWidth, desiredHeight, dimensionTest, outWidth, outHeight, outStride);
1764 // Point sampling group below
1769 * @brief Point sample an image to a new resolution (like GL_NEAREST).
1771 * Template is used purely as a type-safe code generator in this one
1772 * compilation unit. Generated code is inlined into type-specific wrapper
1773 * functions below which are exported to rest of module.
1775 template<typename PIXEL>
1776 inline void PointSampleAddressablePixels(const uint8_t* inPixels,
1777 uint32_t inputWidth,
1778 uint32_t inputHeight,
1779 uint32_t inputStride,
1781 uint32_t desiredWidth,
1782 uint32_t desiredHeight)
1784 DALI_ASSERT_DEBUG(((desiredWidth <= inputWidth && desiredHeight <= inputHeight) ||
1785 outPixels >= inPixels + inputStride * inputHeight * sizeof(PIXEL) || outPixels <= inPixels - desiredWidth * desiredHeight * sizeof(PIXEL)) &&
1786 "The input and output buffers must not overlap for an upscaling.");
1787 DALI_ASSERT_DEBUG(reinterpret_cast<uint64_t>(inPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...).");
1788 DALI_ASSERT_DEBUG(reinterpret_cast<uint64_t>(outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...).");
1790 if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u)
1794 const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
1795 PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
1796 const uint32_t deltaX = (inputWidth << 16u) / desiredWidth;
1797 const uint32_t deltaY = (inputHeight << 16u) / desiredHeight;
1800 for(uint32_t outY = 0; outY < desiredHeight; ++outY)
1802 // Round fixed point y coordinate to nearest integer:
1803 const uint32_t integerY = (inY + (1u << 15u)) >> 16u;
1804 const PIXEL* const inScanline = &inAligned[inputStride * integerY];
1805 PIXEL* const outScanline = &outAligned[desiredWidth * outY];
1807 DALI_ASSERT_DEBUG(integerY < inputHeight);
1808 DALI_ASSERT_DEBUG(reinterpret_cast<const uint8_t*>(inScanline) < (inPixels + inputStride * inputHeight * sizeof(PIXEL)));
1809 DALI_ASSERT_DEBUG(reinterpret_cast<uint8_t*>(outScanline) < (outPixels + desiredWidth * desiredHeight * sizeof(PIXEL)));
1812 for(uint32_t outX = 0; outX < desiredWidth; ++outX)
1814 // Round the fixed-point x coordinate to an integer:
1815 const uint32_t integerX = (inX + (1u << 15u)) >> 16u;
1816 const PIXEL* const inPixelAddress = &inScanline[integerX];
1817 const PIXEL pixel = *inPixelAddress;
1818 outScanline[outX] = pixel;
1828 void PointSample4BPP(const uint8_t* inPixels,
1829 uint32_t inputWidth,
1830 uint32_t inputHeight,
1831 uint32_t inputStride,
1833 uint32_t desiredWidth,
1834 uint32_t desiredHeight)
1836 PointSampleAddressablePixels<uint32_t>(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1840 void PointSample2BPP(const uint8_t* inPixels,
1841 uint32_t inputWidth,
1842 uint32_t inputHeight,
1843 uint32_t inputStride,
1845 uint32_t desiredWidth,
1846 uint32_t desiredHeight)
1848 PointSampleAddressablePixels<uint16_t>(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1852 void PointSample1BPP(const uint8_t* inPixels,
1853 uint32_t inputWidth,
1854 uint32_t inputHeight,
1855 uint32_t inputStride,
1857 uint32_t desiredWidth,
1858 uint32_t desiredHeight)
1860 PointSampleAddressablePixels<uint8_t>(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1864 * RGB888 is a special case as its pixels are not aligned addressable units.
1866 void PointSample3BPP(const uint8_t* inPixels,
1867 uint32_t inputWidth,
1868 uint32_t inputHeight,
1869 uint32_t inputStride,
1871 uint32_t desiredWidth,
1872 uint32_t desiredHeight)
1874 if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u)
1878 const uint32_t BYTES_PER_PIXEL = 3;
1880 // Generate fixed-point 16.16 deltas in input image coordinates:
1881 const uint32_t deltaX = (inputWidth << 16u) / desiredWidth;
1882 const uint32_t deltaY = (inputHeight << 16u) / desiredHeight;
1884 // Step through output image in whole integer pixel steps while tracking the
1885 // corresponding locations in the input image using 16.16 fixed-point
1887 uint32_t inY = 0; //< 16.16 fixed-point input image y-coord.
1888 for(uint32_t outY = 0; outY < desiredHeight; ++outY)
1890 const uint32_t integerY = (inY + (1u << 15u)) >> 16u;
1891 const uint8_t* const inScanline = &inPixels[inputStride * integerY * BYTES_PER_PIXEL];
1892 uint8_t* const outScanline = &outPixels[desiredWidth * outY * BYTES_PER_PIXEL];
1893 uint32_t inX = 0; //< 16.16 fixed-point input image x-coord.
1895 for(uint32_t outX = 0; outX < desiredWidth * BYTES_PER_PIXEL; outX += BYTES_PER_PIXEL)
1897 // Round the fixed-point input coordinate to the address of the input pixel to sample:
1898 const uint32_t integerX = (inX + (1u << 15u)) >> 16u;
1899 const uint8_t* const inPixelAddress = &inScanline[integerX * BYTES_PER_PIXEL];
1901 // Issue loads for all pixel color components up-front:
1902 const uint32_t c0 = inPixelAddress[0];
1903 const uint32_t c1 = inPixelAddress[1];
1904 const uint32_t c2 = inPixelAddress[2];
1905 ///@ToDo: Optimise - Benchmark one 32bit load that will be unaligned 2/3 of the time + 3 rotate and masks, versus these three aligned byte loads, versus using an RGB packed, aligned(1) struct and letting compiler pick a strategy.
1907 // Output the pixel components:
1908 outScanline[outX] = static_cast<uint8_t>(c0);
1909 outScanline[outX + 1] = static_cast<uint8_t>(c1);
1910 outScanline[outX + 2] = static_cast<uint8_t>(c2);
1912 // Increment the fixed-point input coordinate:
1920 // Dispatch to a format-appropriate point sampling function:
1921 void PointSample(const uint8_t* inPixels,
1922 uint32_t inputWidth,
1923 uint32_t inputHeight,
1924 uint32_t inputStride,
1925 Pixel::Format pixelFormat,
1927 uint32_t desiredWidth,
1928 uint32_t desiredHeight)
1930 // Check the pixel format is one that is supported:
1931 if(pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::CHROMINANCE_U || pixelFormat == Pixel::CHROMINANCE_V)
1937 PointSample3BPP(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1940 case Pixel::RGBA8888:
1942 PointSample4BPP(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1948 PointSample2BPP(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1953 case Pixel::CHROMINANCE_U:
1954 case Pixel::CHROMINANCE_V:
1956 PointSample1BPP(inPixels, inputWidth, inputHeight, inputStride, outPixels, desiredWidth, desiredHeight);
1961 DALI_ASSERT_DEBUG(0 == "Inner branch conditions don't match outer branch.");
1967 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not point sampled: unsupported pixel format: %u.\n", uint32_t(pixelFormat));
1971 // Linear sampling group below
1975 /** @brief Blend 4 pixels together using horizontal and vertical weights. */
1976 inline uint8_t BilinearFilter1BPPByte(uint8_t tl, uint8_t tr, uint8_t bl, uint8_t br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical)
1978 return static_cast<uint8_t>(BilinearFilter1Component(tl, tr, bl, br, fractBlendHorizontal, fractBlendVertical));
1981 /** @copydoc BilinearFilter1BPPByte */
1982 inline Pixel2Bytes BilinearFilter2Bytes(Pixel2Bytes tl, Pixel2Bytes tr, Pixel2Bytes bl, Pixel2Bytes br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical)
1985 pixel.l = static_cast<uint8_t>(BilinearFilter1Component(tl.l, tr.l, bl.l, br.l, fractBlendHorizontal, fractBlendVertical));
1986 pixel.a = static_cast<uint8_t>(BilinearFilter1Component(tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical));
1990 /** @copydoc BilinearFilter1BPPByte */
1991 inline Pixel3Bytes BilinearFilterRGB888(Pixel3Bytes tl, Pixel3Bytes tr, Pixel3Bytes bl, Pixel3Bytes br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical)
1994 pixel.r = static_cast<uint8_t>(BilinearFilter1Component(tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical));
1995 pixel.g = static_cast<uint8_t>(BilinearFilter1Component(tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical));
1996 pixel.b = static_cast<uint8_t>(BilinearFilter1Component(tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical));
2000 /** @copydoc BilinearFilter1BPPByte */
2001 inline PixelRGB565 BilinearFilterRGB565(PixelRGB565 tl, PixelRGB565 tr, PixelRGB565 bl, PixelRGB565 br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical)
2003 const PixelRGB565 pixel = static_cast<PixelRGB565>((BilinearFilter1Component(tl >> 11u, tr >> 11u, bl >> 11u, br >> 11u, fractBlendHorizontal, fractBlendVertical) << 11u) +
2004 (BilinearFilter1Component((tl >> 5u) & 63u, (tr >> 5u) & 63u, (bl >> 5u) & 63u, (br >> 5u) & 63u, fractBlendHorizontal, fractBlendVertical) << 5u) +
2005 BilinearFilter1Component(tl & 31u, tr & 31u, bl & 31u, br & 31u, fractBlendHorizontal, fractBlendVertical));
2009 /** @copydoc BilinearFilter1BPPByte */
2010 inline Pixel4Bytes BilinearFilter4Bytes(Pixel4Bytes tl, Pixel4Bytes tr, Pixel4Bytes bl, Pixel4Bytes br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical)
2013 pixel.r = static_cast<uint8_t>(BilinearFilter1Component(tl.r, tr.r, bl.r, br.r, fractBlendHorizontal, fractBlendVertical));
2014 pixel.g = static_cast<uint8_t>(BilinearFilter1Component(tl.g, tr.g, bl.g, br.g, fractBlendHorizontal, fractBlendVertical));
2015 pixel.b = static_cast<uint8_t>(BilinearFilter1Component(tl.b, tr.b, bl.b, br.b, fractBlendHorizontal, fractBlendVertical));
2016 pixel.a = static_cast<uint8_t>(BilinearFilter1Component(tl.a, tr.a, bl.a, br.a, fractBlendHorizontal, fractBlendVertical));
2021 * @brief Generic version of bilinear sampling image resize function.
2022 * @note Limited to one compilation unit and exposed through type-specific
2023 * wrapper functions below.
2027 PIXEL (*BilinearFilter)(PIXEL tl, PIXEL tr, PIXEL bl, PIXEL br, uint32_t fractBlendHorizontal, uint32_t fractBlendVertical),
2028 bool DEBUG_ASSERT_ALIGNMENT>
2029 inline void LinearSampleGeneric(const uint8_t* __restrict__ inPixels,
2030 ImageDimensions inputDimensions,
2031 uint32_t inputStride,
2032 uint8_t* __restrict__ outPixels,
2033 ImageDimensions desiredDimensions)
2035 const uint32_t inputWidth = inputDimensions.GetWidth();
2036 const uint32_t inputHeight = inputDimensions.GetHeight();
2037 const uint32_t desiredWidth = desiredDimensions.GetWidth();
2038 const uint32_t desiredHeight = desiredDimensions.GetHeight();
2040 DALI_ASSERT_DEBUG(((outPixels >= inPixels + inputStride * inputHeight * sizeof(PIXEL)) ||
2041 (inPixels >= outPixels + desiredWidth * desiredHeight * sizeof(PIXEL))) &&
2042 "Input and output buffers cannot overlap.");
2043 if(DEBUG_ASSERT_ALIGNMENT)
2045 DALI_ASSERT_DEBUG(reinterpret_cast<uint64_t>(inPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...).");
2046 DALI_ASSERT_DEBUG(reinterpret_cast<uint64_t>(outPixels) % sizeof(PIXEL) == 0 && "Pixel pointers need to be aligned to the size of the pixels (E.g., 4 bytes for RGBA, 2 bytes for RGB565, ...).");
2049 if(inputWidth < 1u || inputHeight < 1u || desiredWidth < 1u || desiredHeight < 1u)
2053 const PIXEL* const inAligned = reinterpret_cast<const PIXEL*>(inPixels);
2054 PIXEL* const outAligned = reinterpret_cast<PIXEL*>(outPixels);
2055 const uint32_t deltaX = (inputWidth << 16u) / desiredWidth;
2056 const uint32_t deltaY = (inputHeight << 16u) / desiredHeight;
2059 for(uint32_t outY = 0; outY < desiredHeight; ++outY)
2061 PIXEL* const outScanline = &outAligned[desiredWidth * outY];
2063 // Find the two scanlines to blend and the weight to blend with:
2064 const uint32_t integerY1 = inY >> 16u;
2065 const uint32_t integerY2 = integerY1 + 1 >= inputHeight ? integerY1 : integerY1 + 1;
2066 const uint32_t inputYWeight = inY & 65535u;
2068 DALI_ASSERT_DEBUG(integerY1 < inputHeight);
2069 DALI_ASSERT_DEBUG(integerY2 < inputHeight);
2071 const PIXEL* const inScanline1 = &inAligned[inputStride * integerY1];
2072 const PIXEL* const inScanline2 = &inAligned[inputStride * integerY2];
2075 for(uint32_t outX = 0; outX < desiredWidth; ++outX)
2077 // Work out the two pixel scanline offsets for this cluster of four samples:
2078 const uint32_t integerX1 = inX >> 16u;
2079 const uint32_t integerX2 = integerX1 + 1 >= inputWidth ? integerX1 : integerX1 + 1;
2081 // Execute the loads:
2082 const PIXEL pixel1 = inScanline1[integerX1];
2083 const PIXEL pixel2 = inScanline2[integerX1];
2084 const PIXEL pixel3 = inScanline1[integerX2];
2085 const PIXEL pixel4 = inScanline2[integerX2];
2086 ///@ToDo Optimise - for 1 and 2 and 4 byte types to execute a single 2, 4, or 8 byte load per pair (caveat clamping) and let half of them be unaligned.
2088 // Weighted bilinear filter:
2089 const uint32_t inputXWeight = inX & 65535u;
2090 outScanline[outX] = BilinearFilter(pixel1, pixel3, pixel2, pixel4, inputXWeight, inputYWeight);
2100 // Format-specific linear scaling instantiations:
2102 void LinearSample1BPP(const uint8_t* __restrict__ inPixels,
2103 ImageDimensions inputDimensions,
2104 uint32_t inputStride,
2105 uint8_t* __restrict__ outPixels,
2106 ImageDimensions desiredDimensions)
2108 LinearSampleGeneric<uint8_t, BilinearFilter1BPPByte, false>(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions);
2111 void LinearSample2BPP(const uint8_t* __restrict__ inPixels,
2112 ImageDimensions inputDimensions,
2113 uint32_t inputStride,
2114 uint8_t* __restrict__ outPixels,
2115 ImageDimensions desiredDimensions)
2117 LinearSampleGeneric<Pixel2Bytes, BilinearFilter2Bytes, true>(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions);
2120 void LinearSampleRGB565(const uint8_t* __restrict__ inPixels,
2121 ImageDimensions inputDimensions,
2122 uint32_t inputStride,
2123 uint8_t* __restrict__ outPixels,
2124 ImageDimensions desiredDimensions)
2126 LinearSampleGeneric<PixelRGB565, BilinearFilterRGB565, true>(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions);
2129 void LinearSample3BPP(const uint8_t* __restrict__ inPixels,
2130 ImageDimensions inputDimensions,
2131 uint32_t inputStride,
2132 uint8_t* __restrict__ outPixels,
2133 ImageDimensions desiredDimensions)
2135 LinearSampleGeneric<Pixel3Bytes, BilinearFilterRGB888, false>(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions);
2138 void LinearSample4BPP(const uint8_t* __restrict__ inPixels,
2139 ImageDimensions inputDimensions,
2140 uint32_t inputStride,
2141 uint8_t* __restrict__ outPixels,
2142 ImageDimensions desiredDimensions)
2144 LinearSampleGeneric<Pixel4Bytes, BilinearFilter4Bytes, true>(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions);
2147 // Dispatch to a format-appropriate linear sampling function:
2148 void LinearSample(const uint8_t* __restrict__ inPixels,
2149 ImageDimensions inDimensions,
2151 Pixel::Format pixelFormat,
2152 uint8_t* __restrict__ outPixels,
2153 ImageDimensions outDimensions)
2155 // Check the pixel format is one that is supported:
2156 if(pixelFormat == Pixel::RGB888 || pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8 || pixelFormat == Pixel::LA88 || pixelFormat == Pixel::RGB565 || pixelFormat == Pixel::CHROMINANCE_U || pixelFormat == Pixel::CHROMINANCE_V)
2162 LinearSample3BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2165 case Pixel::RGBA8888:
2167 LinearSample4BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2172 case Pixel::CHROMINANCE_U:
2173 case Pixel::CHROMINANCE_V:
2175 LinearSample1BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2180 LinearSample2BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2185 LinearSampleRGB565(inPixels, inDimensions, inStride, outPixels, outDimensions);
2190 DALI_ASSERT_DEBUG(0 == "Inner branch conditions don't match outer branch.");
2196 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not linear sampled: unsupported pixel format: %u.\n", uint32_t(pixelFormat));
2200 void Resample(const uint8_t* __restrict__ inPixels,
2201 ImageDimensions inputDimensions,
2202 uint32_t inputStride,
2203 uint8_t* __restrict__ outPixels,
2204 ImageDimensions desiredDimensions,
2205 Resampler::Filter filterType,
2209 // Got from the test.cpp of the ImageResampler lib.
2210 const float ONE_DIV_255 = 1.0f / 255.0f;
2211 const int MAX_UNSIGNED_CHAR = std::numeric_limits<uint8_t>::max();
2212 const int LINEAR_TO_SRGB_TABLE_SIZE = 4096;
2213 const int ALPHA_CHANNEL = hasAlpha ? (numChannels - 1) : 0;
2215 static bool loadColorSpaces = true;
2216 static float srgbToLinear[MAX_UNSIGNED_CHAR + 1];
2217 static uint8_t linearToSrgb[LINEAR_TO_SRGB_TABLE_SIZE];
2219 if(loadColorSpaces) // Only create the color space conversions on the first execution
2221 loadColorSpaces = false;
2223 for(int i = 0; i <= MAX_UNSIGNED_CHAR; ++i)
2225 srgbToLinear[i] = pow(static_cast<float>(i) * ONE_DIV_255, DEFAULT_SOURCE_GAMMA);
2228 const float invLinearToSrgbTableSize = 1.0f / static_cast<float>(LINEAR_TO_SRGB_TABLE_SIZE);
2229 const float invSourceGamma = 1.0f / DEFAULT_SOURCE_GAMMA;
2231 for(int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i)
2233 int k = static_cast<int>(255.0f * pow(static_cast<float>(i) * invLinearToSrgbTableSize, invSourceGamma) + 0.5f);
2238 else if(k > MAX_UNSIGNED_CHAR)
2240 k = MAX_UNSIGNED_CHAR;
2242 linearToSrgb[i] = static_cast<uint8_t>(k);
2246 std::vector<Resampler*> resamplers(numChannels);
2247 std::vector<Vector<float>> samples(numChannels);
2249 const int srcWidth = inputDimensions.GetWidth();
2250 const int srcHeight = inputDimensions.GetHeight();
2251 const int dstWidth = desiredDimensions.GetWidth();
2252 const int dstHeight = desiredDimensions.GetHeight();
2254 // Now create a Resampler instance for each component to process. The first instance will create new contributor tables, which are shared by the resamplers
2255 // used for the other components (a memory and slight cache efficiency optimization).
2256 resamplers[0] = new Resampler(srcWidth,
2260 Resampler::BOUNDARY_CLAMP,
2261 0.0f, // sample_low,
2262 1.0f, // sample_high. Clamp output samples to specified range, or disable clamping if sample_low >= sample_high.
2263 filterType, // The type of filter.
2265 NULL, // Pclist_y. Optional pointers to contributor lists from another instance of a Resampler.
2266 FILTER_SCALE, // src_x_ofs,
2267 FILTER_SCALE); // src_y_ofs. Offset input image by specified amount (fractional values okay).
2268 samples[0].ResizeUninitialized(srcWidth);
2269 for(int i = 1; i < numChannels; ++i)
2271 resamplers[i] = new Resampler(srcWidth,
2275 Resampler::BOUNDARY_CLAMP,
2279 resamplers[0]->get_clist_x(),
2280 resamplers[0]->get_clist_y(),
2283 samples[i].ResizeUninitialized(srcWidth);
2286 const int srcPitch = inputStride * numChannels;
2287 const int dstPitch = dstWidth * numChannels;
2290 for(int srcY = 0; srcY < srcHeight; ++srcY)
2292 const uint8_t* pSrc = &inPixels[srcY * srcPitch];
2294 for(int x = 0; x < srcWidth; ++x)
2296 for(int c = 0; c < numChannels; ++c)
2298 if(c == ALPHA_CHANNEL && hasAlpha)
2300 samples[c][x] = *pSrc++ * ONE_DIV_255;
2304 samples[c][x] = srgbToLinear[*pSrc++];
2309 for(int c = 0; c < numChannels; ++c)
2311 if(!resamplers[c]->put_line(&samples[c][0]))
2313 DALI_ASSERT_DEBUG(!"Out of memory");
2320 for(compIndex = 0; compIndex < numChannels; ++compIndex)
2322 const float* pOutputSamples = resamplers[compIndex]->get_line();
2328 const bool isAlphaChannel = (compIndex == ALPHA_CHANNEL && hasAlpha);
2329 DALI_ASSERT_DEBUG(dstY < dstHeight);
2330 uint8_t* pDst = &outPixels[dstY * dstPitch + compIndex];
2332 for(int x = 0; x < dstWidth; ++x)
2336 int c = static_cast<int>(255.0f * pOutputSamples[x] + 0.5f);
2341 else if(c > MAX_UNSIGNED_CHAR)
2343 c = MAX_UNSIGNED_CHAR;
2345 *pDst = static_cast<uint8_t>(c);
2349 int j = static_cast<int>(LINEAR_TO_SRGB_TABLE_SIZE * pOutputSamples[x] + 0.5f);
2354 else if(j >= LINEAR_TO_SRGB_TABLE_SIZE)
2356 j = LINEAR_TO_SRGB_TABLE_SIZE - 1;
2358 *pDst = linearToSrgb[j];
2361 pDst += numChannels;
2364 if(compIndex < numChannels)
2373 // Delete the resamplers.
2374 for(int i = 0; i < numChannels; ++i)
2376 delete resamplers[i];
2380 void LanczosSample4BPP(const uint8_t* __restrict__ inPixels,
2381 ImageDimensions inputDimensions,
2382 uint32_t inputStride,
2383 uint8_t* __restrict__ outPixels,
2384 ImageDimensions desiredDimensions)
2386 Resample(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions, Resampler::LANCZOS4, 4, true);
2389 void LanczosSample1BPP(const uint8_t* __restrict__ inPixels,
2390 ImageDimensions inputDimensions,
2391 uint32_t inputStride,
2392 uint8_t* __restrict__ outPixels,
2393 ImageDimensions desiredDimensions)
2396 Resample(inPixels, inputDimensions, inputStride, outPixels, desiredDimensions, Resampler::LANCZOS4, 1, false);
2399 // Dispatch to a format-appropriate third-party resampling function:
2400 void LanczosSample(const uint8_t* __restrict__ inPixels,
2401 ImageDimensions inDimensions,
2403 Pixel::Format pixelFormat,
2404 uint8_t* __restrict__ outPixels,
2405 ImageDimensions outDimensions)
2407 // Check the pixel format is one that is supported:
2408 if(pixelFormat == Pixel::RGBA8888 || pixelFormat == Pixel::BGRA8888 || pixelFormat == Pixel::L8 || pixelFormat == Pixel::A8)
2412 case Pixel::RGBA8888:
2413 case Pixel::BGRA8888:
2415 LanczosSample4BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2421 LanczosSample1BPP(inPixels, inDimensions, inStride, outPixels, outDimensions);
2426 DALI_ASSERT_DEBUG(0 == "Inner branch conditions don't match outer branch.");
2432 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Bitmap was not lanczos sampled: unsupported pixel format: %u.\n", static_cast<uint32_t>(pixelFormat));
2436 void RotateByShear(const uint8_t* const pixelsIn,
2442 uint8_t*& pixelsOut,
2444 uint32_t& heightOut)
2446 // @note Code got from https://www.codeproject.com/Articles/202/High-quality-image-rotation-rotate-by-shear by Eran Yariv.
2448 // Do first the fast rotations to transform the angle into a (-45..45] range.
2450 bool fastRotationPerformed = false;
2451 if((radians > Math::PI_4) && (radians <= RAD_135))
2453 // Angle in (45.0 .. 135.0]
2454 // Rotate image by 90 degrees into temporary image,
2455 // so it requires only an extra rotation angle
2456 // of -45.0 .. +45.0 to complete rotation.
2457 fastRotationPerformed = Rotate90(pixelsIn,
2466 if(!fastRotationPerformed)
2468 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n");
2469 // The fast rotation failed.
2473 radians -= Math::PI_2;
2475 else if((radians > RAD_135) && (radians <= RAD_225))
2477 // Angle in (135.0 .. 225.0]
2478 // Rotate image by 180 degrees into temporary image,
2479 // so it requires only an extra rotation angle
2480 // of -45.0 .. +45.0 to complete rotation.
2482 fastRotationPerformed = Rotate180(pixelsIn,
2489 if(!fastRotationPerformed)
2491 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n");
2492 // The fast rotation failed.
2496 radians -= Math::PI;
2498 heightOut = heightIn;
2500 else if((radians > RAD_225) && (radians <= RAD_315))
2502 // Angle in (225.0 .. 315.0]
2503 // Rotate image by 270 degrees into temporary image,
2504 // so it requires only an extra rotation angle
2505 // of -45.0 .. +45.0 to complete rotation.
2507 fastRotationPerformed = Rotate270(pixelsIn,
2516 if(!fastRotationPerformed)
2518 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "fast rotation failed\n");
2519 // The fast rotation failed.
2526 if(fabs(radians) < Dali::Math::MACHINE_EPSILON_10)
2528 // Nothing else to do if the angle is zero.
2529 // The rotation angle was 90, 180 or 270.
2531 // @note Allocated memory by 'Fast Rotations', if any, has to be freed by the called to this function.
2535 const uint8_t* const firstHorizontalSkewPixelsIn = fastRotationPerformed ? pixelsOut : pixelsIn;
2536 std::unique_ptr<uint8_t, void (*)(void*)> tmpPixelsInPtr((fastRotationPerformed ? pixelsOut : nullptr), free);
2538 uint32_t stride = fastRotationPerformed ? widthOut : strideIn;
2540 // Reset the input/output
2542 heightIn = heightOut;
2543 pixelsOut = nullptr;
2545 const float angleSinus = sin(radians);
2546 const float angleCosinus = cos(radians);
2547 const float angleTangent = tan(0.5f * radians);
2549 ///////////////////////////////////////
2550 // Perform 1st shear (horizontal)
2551 ///////////////////////////////////////
2553 // Calculate first shear (horizontal) destination image dimensions
2555 widthOut = widthIn + static_cast<uint32_t>(fabs(angleTangent) * static_cast<float>(heightIn));
2556 heightOut = heightIn;
2558 // Allocate the buffer for the 1st shear
2559 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
2561 if(nullptr == pixelsOut)
2563 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
2567 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n");
2569 // The deleter of the tmpPixelsInPtr unique pointer is called freeing the memory allocated by the 'Fast rotations'.
2570 // Nothing else to do if the memory allocation fails.
2574 for(uint32_t y = 0u; y < heightOut; ++y)
2576 const float shear = angleTangent * ((angleTangent >= 0.f) ? (0.5f + static_cast<float>(y)) : (0.5f + static_cast<float>(y) - static_cast<float>(heightOut)));
2578 const int intShear = static_cast<int>(floor(shear));
2579 HorizontalSkew(firstHorizontalSkewPixelsIn, widthIn, stride, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast<float>(intShear));
2582 // Reset the 'pixel in' pointer with the output of the 'First Horizontal Skew' and free the memory allocated by the 'Fast Rotations'.
2583 tmpPixelsInPtr.reset(pixelsOut);
2584 uint32_t tmpWidthIn = widthOut;
2585 uint32_t tmpHeightIn = heightOut;
2587 // Reset the input/output
2588 pixelsOut = nullptr;
2590 ///////////////////////////////////////
2591 // Perform 2nd shear (vertical)
2592 ///////////////////////////////////////
2594 // Calc 2nd shear (vertical) destination image dimensions
2595 heightOut = static_cast<uint32_t>(static_cast<float>(widthIn) * fabs(angleSinus) + static_cast<float>(heightIn) * angleCosinus);
2597 // Allocate the buffer for the 2nd shear
2598 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
2600 if(nullptr == pixelsOut)
2602 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
2606 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n");
2607 // The deleter of the tmpPixelsInPtr unique pointer is called freeing the memory allocated by the 'First Horizontal Skew'.
2608 // Nothing else to do if the memory allocation fails.
2612 // Variable skew offset
2613 float offset = angleSinus * ((angleSinus > 0.f) ? static_cast<float>(widthIn - 1u) : -(static_cast<float>(widthIn) - static_cast<float>(widthOut)));
2615 uint32_t column = 0u;
2616 for(column = 0u; column < widthOut; ++column, offset -= angleSinus)
2618 const int32_t shear = static_cast<int32_t>(floor(offset));
2619 VerticalSkew(tmpPixelsInPtr.get(), tmpWidthIn, tmpHeightIn, tmpWidthIn, pixelSize, pixelsOut, widthOut, heightOut, column, shear, offset - static_cast<float>(shear));
2621 // Reset the 'pixel in' pointer with the output of the 'Vertical Skew' and free the memory allocated by the 'First Horizontal Skew'.
2622 // Reset the input/output
2623 tmpPixelsInPtr.reset(pixelsOut);
2624 tmpWidthIn = widthOut;
2625 tmpHeightIn = heightOut;
2626 pixelsOut = nullptr;
2628 ///////////////////////////////////////
2629 // Perform 3rd shear (horizontal)
2630 ///////////////////////////////////////
2632 // Calc 3rd shear (horizontal) destination image dimensions
2633 widthOut = static_cast<uint32_t>(static_cast<float>(heightIn) * fabs(angleSinus) + static_cast<float>(widthIn) * angleCosinus) + 1u;
2635 // Allocate the buffer for the 3rd shear
2636 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
2638 if(nullptr == pixelsOut)
2640 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
2644 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n");
2645 // The deleter of the tmpPixelsInPtr unique pointer is called freeing the memory allocated by the 'Vertical Skew'.
2646 // Nothing else to do if the memory allocation fails.
2650 offset = (angleSinus >= 0.f) ? -angleSinus * angleTangent * static_cast<float>(widthIn - 1u) : angleTangent * (static_cast<float>(widthIn - 1u) * -angleSinus + (1.f - static_cast<float>(heightOut)));
2652 for(uint32_t y = 0u; y < heightOut; ++y, offset += angleTangent)
2654 const int32_t shear = static_cast<int32_t>(floor(offset));
2655 HorizontalSkew(tmpPixelsInPtr.get(), tmpWidthIn, tmpWidthIn, pixelSize, pixelsOut, widthOut, y, shear, offset - static_cast<float>(shear));
2658 // The deleter of the tmpPixelsInPtr unique pointer is called freeing the memory allocated by the 'Vertical Skew'.
2659 // @note Allocated memory by the last 'Horizontal Skew' has to be freed by the caller to this function.
2662 void HorizontalShear(const uint8_t* const pixelsIn,
2668 uint8_t*& pixelsOut,
2670 uint32_t& heightOut)
2672 // Calculate the destination image dimensions.
2674 const float absRadians = fabs(radians);
2676 if(absRadians > Math::PI_4)
2678 // Can't shear more than 45 degrees.
2682 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "Can't shear more than 45 degrees (PI/4 radians). radians : %f\n", radians);
2686 widthOut = widthIn + static_cast<uint32_t>(ceil(absRadians * static_cast<float>(heightIn)));
2687 heightOut = heightIn;
2689 // Allocate the buffer for the shear.
2690 pixelsOut = static_cast<uint8_t*>(malloc(widthOut * heightOut * pixelSize));
2692 if(nullptr == pixelsOut)
2694 DALI_LOG_ERROR("malloc is failed. request malloc size : %u x %u x %u\n", widthOut, heightOut, pixelSize);
2698 DALI_LOG_INFO(gImageOpsLogFilter, Dali::Integration::Log::Verbose, "malloc failed to allocate memory\n");
2702 for(uint32_t y = 0u; y < heightOut; ++y)
2704 const float shear = radians * ((radians >= 0.f) ? (0.5f + static_cast<float>(y)) : (0.5f + static_cast<float>(y) - static_cast<float>(heightOut)));
2706 const int32_t intShear = static_cast<int32_t>(floor(shear));
2707 HorizontalSkew(pixelsIn, widthIn, strideIn, pixelSize, pixelsOut, widthOut, y, intShear, shear - static_cast<float>(intShear));
2711 } /* namespace Platform */
2712 } /* namespace Internal */
2713 } /* namespace Dali */